No bufclosing of handles after track change
[Rockbox.git] / firmware / powermgmt.c
blobfcc303086120bc402df179d957156416cf124dd3
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;
79 #if CONFIG_CHARGING >= CHARGING_MONITOR
80 charge_state_type charge_state; /* charging mode */
81 #endif
83 #if CONFIG_CHARGING
84 charger_input_state_type charger_input_state IDATA_ATTR;
85 #endif
87 #ifdef SIMULATOR /***********************************************************/
89 #define BATT_MINMVOLT 2500 /* minimum millivolts of battery */
90 #define BATT_MAXMVOLT 4500 /* maximum millivolts of battery */
91 #define BATT_MAXRUNTIME (10 * 60) /* maximum runtime with full battery in minutes */
93 static unsigned int batt_millivolts = (unsigned int)BATT_MAXMVOLT;
94 static int batt_level = 100; /* battery capacity level in percent */
95 static int batt_time = BATT_MAXRUNTIME; /* estimated remaining time in minutes */
96 static time_t last_change = 0;
98 static void battery_status_update(void)
100 time_t now;
102 time(&now);
103 if (last_change < now) {
104 last_change = now;
106 /* change the values: */
107 batt_millivolts -= (unsigned int)(BATT_MAXMVOLT - BATT_MINMVOLT) / 101;
108 if (batt_millivolts < (unsigned int)BATT_MINMVOLT)
109 batt_millivolts = (unsigned int)BATT_MAXMVOLT;
111 batt_level = 100 * (batt_millivolts - BATT_MINMVOLT) / (BATT_MAXMVOLT - BATT_MINMVOLT);
112 batt_time = batt_level * BATT_MAXRUNTIME / 100;
116 void battery_read_info(int *voltage, int *level)
118 battery_status_update();
120 if (voltage)
121 *voltage = batt_millivolts;
123 if (level)
124 *level = batt_level;
127 unsigned int battery_voltage(void)
129 battery_status_update();
130 return batt_millivolts;
133 int battery_level(void)
135 battery_status_update();
136 return batt_level;
139 int battery_time(void)
141 battery_status_update();
142 return batt_time;
145 bool battery_level_safe(void)
147 return battery_level() >= 10;
150 void set_poweroff_timeout(int timeout)
152 (void)timeout;
155 void set_battery_capacity(int capacity)
157 (void)capacity;
160 #if BATTERY_TYPES_COUNT > 1
161 void set_battery_type(int type)
163 (void)type;
165 #endif
167 void reset_poweroff_timer(void)
171 #else /* not SIMULATOR ******************************************************/
173 static const unsigned char poweroff_idle_timeout_value[15] =
175 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 30, 45, 60
178 #if CONFIG_CHARGING == CHARGING_CONTROL
179 int long_delta; /* long term delta battery voltage */
180 int short_delta; /* short term delta battery voltage */
181 bool disk_activity_last_cycle = false; /* flag set to aid charger time
182 * calculation */
183 char power_message[POWER_MESSAGE_LEN] = ""; /* message that's shown in
184 debug menu */
185 /* percentage at which charging
186 starts */
187 int powermgmt_last_cycle_startstop_min = 0; /* how many minutes ago was the
188 charging started or
189 stopped? */
190 int powermgmt_last_cycle_level = 0; /* which level had the
191 batteries at this time? */
192 int trickle_sec = 0; /* how many seconds should the
193 charger be enabled per
194 minute for trickle
195 charging? */
196 int pid_p = 0; /* PID proportional term */
197 int pid_i = 0; /* PID integral term */
198 #endif /* CONFIG_CHARGING == CHARGING_CONTROL */
201 * Average battery voltage and charger voltage, filtered via a digital
202 * exponential filter.
204 static unsigned int avgbat; /* average battery voltage (filtering) */
205 static unsigned int battery_millivolts;/* filtered battery voltage, millivolts */
207 #ifdef HAVE_CHARGE_CTRL
208 #define BATT_AVE_SAMPLES 32 /* filter constant / @ 2Hz sample rate */
209 #else
210 #define BATT_AVE_SAMPLES 128 /* slw filter constant for all others */
211 #endif
213 /* battery level (0-100%) of this minute, updated once per minute */
214 static int battery_percent = -1;
215 static int battery_capacity = BATTERY_CAPACITY_DEFAULT; /* default value, mAh */
216 static int battery_type = 0;
218 /* Power history: power_history[0] is the newest sample */
219 unsigned short power_history[POWER_HISTORY_LEN];
221 static char power_stack[DEFAULT_STACK_SIZE/2 + DEBUG_STACK];
222 static const char power_thread_name[] = "power";
224 static int poweroff_timeout = 0;
225 static int powermgmt_est_runningtime_min = -1;
227 static bool sleeptimer_active = false;
228 static long sleeptimer_endtick;
230 static long last_event_tick;
232 static int voltage_to_battery_level(int battery_millivolts);
233 static void battery_status_update(void);
234 static int runcurrent(void);
236 void battery_read_info(int *voltage, int *level)
238 int millivolts = battery_adc_voltage();
240 if (voltage)
241 *voltage = millivolts;
243 if (level)
244 *level = voltage_to_battery_level(millivolts);
247 void reset_poweroff_timer(void)
249 last_event_tick = current_tick;
252 #if BATTERY_TYPES_COUNT > 1
253 void set_battery_type(int type)
255 if (type != battery_type) {
256 battery_type = type;
257 battery_status_update(); /* recalculate the battery status */
260 #endif
262 void set_battery_capacity(int capacity)
264 battery_capacity = capacity;
265 if (battery_capacity > BATTERY_CAPACITY_MAX)
266 battery_capacity = BATTERY_CAPACITY_MAX;
267 if (battery_capacity < BATTERY_CAPACITY_MIN)
268 battery_capacity = BATTERY_CAPACITY_MIN;
269 battery_status_update(); /* recalculate the battery status */
272 int battery_time(void)
274 return powermgmt_est_runningtime_min;
277 /* Returns battery level in percent */
278 int battery_level(void)
280 return battery_percent;
283 /* Returns filtered battery voltage [millivolts] */
284 unsigned int battery_voltage(void)
286 return battery_millivolts;
289 /* Tells if the battery level is safe for disk writes */
290 bool battery_level_safe(void)
292 return battery_millivolts > battery_level_dangerous[battery_type];
295 void set_poweroff_timeout(int timeout)
297 poweroff_timeout = timeout;
300 void set_sleep_timer(int seconds)
302 if(seconds) {
303 sleeptimer_active = true;
304 sleeptimer_endtick = current_tick + seconds * HZ;
306 else {
307 sleeptimer_active = false;
308 sleeptimer_endtick = 0;
312 int get_sleep_timer(void)
314 if(sleeptimer_active)
315 return (sleeptimer_endtick - current_tick) / HZ;
316 else
317 return 0;
320 /* look into the percent_to_volt_* table and get a realistic battery level */
321 static int voltage_to_percent(int voltage, const short* table)
323 if (voltage <= table[0])
324 return 0;
325 else
326 if (voltage >= table[10])
327 return 100;
328 else {
329 /* search nearest value */
330 int i = 0;
331 while ((i < 10) && (table[i+1] < voltage))
332 i++;
333 /* interpolate linear between the smaller and greater value */
334 return (i * 10) /* Tens digit, 10% per entry */
335 + (((voltage - table[i]) * 10)
336 / (table[i+1] - table[i])); /* Ones digit: interpolated */
340 /* update battery level and estimated runtime, called once per minute or
341 * when battery capacity / type settings are changed */
342 static int voltage_to_battery_level(int battery_millivolts)
344 int level;
346 #if defined(CONFIG_CHARGER) \
347 && (defined(IRIVER_H100_SERIES) || defined(IRIVER_H300_SERIES))
348 /* Checking for iriver is a temporary kludge.
349 * This code needs rework/unification */
350 if (charger_input_state == NO_CHARGER) {
351 /* discharging. calculate new battery level and average with last */
352 level = voltage_to_percent(battery_millivolts,
353 percent_to_volt_discharge[battery_type]);
354 if (level != (battery_percent - 1))
355 level = (level + battery_percent + 1) / 2;
357 else if (charger_input_state == CHARGER_UNPLUGGED) {
358 /* just unplugged. adjust filtered values */
359 battery_millivolts -= percent_to_volt_charge[battery_percent/10] -
360 percent_to_volt_discharge[0][battery_percent/10];
361 avgbat = battery_millivolts * 1000 * BATT_AVE_SAMPLES;
362 level = battery_percent;
364 else if (charger_input_state == CHARGER_PLUGGED) {
365 /* just plugged in. adjust battery values */
366 battery_millivolts += percent_to_volt_charge[battery_percent/10] -
367 percent_to_volt_discharge[0][battery_percent/10];
368 avgbat = battery_millivolts * 1000 * BATT_AVE_SAMPLES;
369 level = MIN(12 * battery_percent / 10, 99);
371 else { /* charging. calculate new battery level */
372 level = voltage_to_percent(battery_millivolts,
373 percent_to_volt_charge);
375 #elif CONFIG_CHARGING >= CHARGING_MONITOR
376 if (charge_state == DISCHARGING) {
377 level = voltage_to_percent(battery_millivolts,
378 percent_to_volt_discharge[battery_type]);
380 else if (charge_state == CHARGING) {
381 /* battery level is defined to be < 100% until charging is finished */
382 level = MIN(voltage_to_percent(battery_millivolts,
383 percent_to_volt_charge), 99);
385 else { /* in topoff/trickle charge, battery is by definition 100% full */
386 level = 100;
388 #else
389 /* always use the discharge table */
390 level = voltage_to_percent(battery_millivolts,
391 percent_to_volt_discharge[battery_type]);
392 #endif
394 return level;
397 static void battery_status_update(void)
399 int level = voltage_to_battery_level(battery_millivolts);
402 /* calculate estimated remaining running time */
403 /* discharging: remaining running time */
404 /* charging: remaining charging time */
405 #if CONFIG_CHARGING >= CHARGING_MONITOR
406 if (charge_state == CHARGING) {
407 powermgmt_est_runningtime_min = (100 - level) * battery_capacity * 60
408 / 100 / (CURRENT_MAX_CHG - runcurrent());
410 else
411 #elif CONFIG_CHARGING \
412 && (defined(IRIVER_H100_SERIES) || defined(IRIVER_H300_SERIES))
413 /* Checking for iriver is a temporary kludge.
414 * This code needs rework/unification */
415 if (charger_inserted()) {
416 #ifdef IRIVER_H300_SERIES
417 /* H300_SERIES use CURRENT_MAX_CHG for basic charge time (80%)
418 * plus 110 min top off charge time */
419 powermgmt_est_runningtime_min = ((100-level) * battery_capacity * 80
420 /100 / CURRENT_MAX_CHG) + 110;
421 #else
422 /* H100_SERIES scaled for 160 min basic charge time (80%) on
423 * 1600 mAh battery plus 110 min top off charge time */
424 powermgmt_est_runningtime_min = ((100 - level) * battery_capacity
425 / 993) + 110;
426 #endif
427 level = (level * 80) / 100;
428 if (level > 72) { /* > 91% */
429 int i = POWER_HISTORY_LEN;
430 int d = 1;
431 #ifdef HAVE_CHARGE_STATE
432 if (charge_state == DISCHARGING)
433 d = -2;
434 #endif
435 while ((i > 2) && (d > 0)) /* search zero or neg. delta */
436 d = power_history[0] - power_history[--i];
437 if ((((d == 0) && (i > 6)) || (d == -1)) && (i < 118)) {
438 /* top off charging */
439 level = MIN(80 + (i*19 / 113), 99); /* show 81% .. 99% */
440 powermgmt_est_runningtime_min = MAX(116 - i, 0);
442 else if ((d < 0) || (i > 117)) {
443 /* charging finished */
444 level = 100;
445 powermgmt_est_runningtime_min = battery_capacity * 60
446 / runcurrent();
450 else
451 #endif /* BATT_LIPOL1300 */
453 if ((battery_millivolts + 20) > percent_to_volt_discharge[0][0])
454 powermgmt_est_runningtime_min = (level + battery_percent) * 60 *
455 battery_capacity / 200 / runcurrent();
456 else
457 powermgmt_est_runningtime_min = (battery_millivolts -
458 battery_level_shutoff[0]) / 2;
461 battery_percent = level;
465 * We shut off in the following cases:
466 * 1) The unit is idle, not playing music
467 * 2) The unit is playing music, but is paused
468 * 3) The battery level has reached shutdown limit
470 * We do not shut off in the following cases:
471 * 1) The USB is connected
472 * 2) The charger is connected
473 * 3) We are recording, or recording with pause
474 * 4) The radio is playing
476 static void handle_auto_poweroff(void)
478 long timeout = poweroff_idle_timeout_value[poweroff_timeout]*60*HZ;
479 int audio_stat = audio_status();
481 #if CONFIG_CHARGING
483 * Inhibit shutdown as long as the charger is plugged in. If it is
484 * unplugged, wait for a timeout period and then shut down.
486 if(charger_input_state == CHARGER || audio_stat == AUDIO_STATUS_PLAY) {
487 last_event_tick = current_tick;
489 #endif
491 #ifndef NO_LOW_BATTERY_SHUTDOWN
492 /* switch off unit if battery level is too low for reliable operation */
493 if(battery_millivolts < battery_level_shutoff[battery_type]) {
494 if(!shutdown_timeout) {
495 backlight_on();
496 sys_poweroff();
499 #endif
501 if(timeout &&
502 #if CONFIG_TUNER && !defined(BOOTLOADER)
503 (!(get_radio_status() & FMRADIO_PLAYING)) &&
504 #endif
505 !usb_inserted() &&
506 ((audio_stat == 0) ||
507 ((audio_stat == (AUDIO_STATUS_PLAY | AUDIO_STATUS_PAUSE)) &&
508 !sleeptimer_active)))
510 if(TIME_AFTER(current_tick, last_event_tick + timeout) &&
511 TIME_AFTER(current_tick, last_disk_activity + timeout))
513 sys_poweroff();
516 else
518 /* Handle sleeptimer */
519 if(sleeptimer_active && !usb_inserted())
521 if(TIME_AFTER(current_tick, sleeptimer_endtick))
523 audio_stop();
524 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
525 if((charger_input_state == CHARGER) ||
526 (charger_input_state == CHARGER_PLUGGED))
528 DEBUGF("Sleep timer timeout. Stopping...\n");
529 set_sleep_timer(0);
530 backlight_off(); /* Nighty, nighty... */
532 else
533 #endif
535 DEBUGF("Sleep timer timeout. Shutting off...\n");
536 sys_poweroff();
544 * Estimate how much current we are drawing just to run.
546 static int runcurrent(void)
548 int current;
550 #if MEM == 8 && !defined(HAVE_MMC)
551 /* assuming 192 kbps, the running time is 22% longer with 8MB */
552 current = (CURRENT_NORMAL*100/122);
553 #else
554 current = CURRENT_NORMAL;
555 #endif /* MEM == 8 */
557 if(usb_inserted()
558 #if defined(HAVE_USB_POWER)
559 #if (CURRENT_USB < CURRENT_NORMAL)
560 || usb_powered()
561 #else
562 && !usb_powered()
563 #endif
564 #endif
567 current = CURRENT_USB;
570 #if defined(HAVE_BACKLIGHT) && !defined(BOOTLOADER)
571 if (backlight_get_current_timeout() == 0) /* LED always on */
572 current += CURRENT_BACKLIGHT;
573 #endif
575 #if defined(HAVE_RECORDING) && defined(CURRENT_RECORD)
576 if (audio_status() & AUDIO_STATUS_RECORD)
577 current += CURRENT_RECORD;
578 #endif
580 #ifdef HAVE_SPDIF_POWER
581 if (spdif_powered())
582 current += CURRENT_SPDIF_OUT;
583 #endif
585 #ifdef HAVE_REMOTE_LCD
586 if (remote_detect())
587 current += CURRENT_REMOTE;
588 #endif
590 return(current);
594 /* Check to see whether or not we've received an alarm in the last second */
595 #ifdef HAVE_RTC_ALARM
596 static void power_thread_rtc_process(void)
598 if (rtc_check_alarm_flag()) {
599 rtc_enable_alarm(false);
602 #endif
605 * This function is called to do the relativly long sleep waits from within the
606 * main power_thread loop while at the same time servicing any other periodic
607 * functions in the power thread which need to be called at a faster periodic
608 * rate than the slow periodic rate of the main power_thread loop.
610 * While we are waiting for the time to expire, we average the battery
611 * voltages.
613 static void power_thread_sleep(int ticks)
615 int small_ticks;
617 while (ticks > 0) {
619 #if CONFIG_CHARGING
621 * Detect charger plugged/unplugged transitions. On a plugged or
622 * unplugged event, we return immediately, run once through the main
623 * loop (including the subroutines), and end up back here where we
624 * transition to the appropriate steady state charger on/off state.
626 if(charger_inserted()
627 #ifdef HAVE_USB_POWER /* USB powered or USB inserted both provide power */
628 || usb_powered()
629 #if CONFIG_CHARGING
630 || (usb_inserted() && usb_charging_enabled())
631 #endif
632 #endif
634 switch(charger_input_state) {
635 case NO_CHARGER:
636 case CHARGER_UNPLUGGED:
637 charger_input_state = CHARGER_PLUGGED;
638 return;
639 case CHARGER_PLUGGED:
640 queue_broadcast(SYS_CHARGER_CONNECTED, 0);
641 charger_input_state = CHARGER;
642 break;
643 case CHARGER:
644 break;
646 } else { /* charger not inserted */
647 switch(charger_input_state) {
648 case NO_CHARGER:
649 break;
650 case CHARGER_UNPLUGGED:
651 queue_broadcast(SYS_CHARGER_DISCONNECTED, 0);
652 charger_input_state = NO_CHARGER;
653 break;
654 case CHARGER_PLUGGED:
655 case CHARGER:
656 charger_input_state = CHARGER_UNPLUGGED;
657 return;
660 #endif
661 #if CONFIG_CHARGING == CHARGING_MONITOR
662 switch (charger_input_state) {
663 case CHARGER_UNPLUGGED:
664 case NO_CHARGER:
665 charge_state = DISCHARGING;
666 break;
667 case CHARGER_PLUGGED:
668 case CHARGER:
669 if (charging_state()) {
670 charge_state = CHARGING;
671 } else {
672 charge_state = DISCHARGING;
674 break;
677 #endif /* CONFIG_CHARGING == CHARGING_MONITOR */
679 small_ticks = MIN(HZ/2, ticks);
680 sleep(small_ticks);
681 ticks -= small_ticks;
683 /* If the power off timeout expires, the main thread has failed
684 to shut down the system, and we need to force a power off */
685 if(shutdown_timeout) {
686 shutdown_timeout -= small_ticks;
687 if(shutdown_timeout <= 0)
688 power_off();
691 #ifdef HAVE_RTC_ALARM
692 power_thread_rtc_process();
693 #endif
696 * Do a digital exponential filter. We don't sample the battery if
697 * the disk is spinning unless we are in USB mode (the disk will most
698 * likely always be spinning in USB mode).
700 if (!ata_disk_is_active() || usb_inserted()) {
701 avgbat += battery_adc_voltage() - (avgbat / BATT_AVE_SAMPLES);
703 * battery_millivolts is the millivolt-scaled filtered battery value.
705 battery_millivolts = avgbat / BATT_AVE_SAMPLES;
707 /* update battery status every time an update is available */
708 battery_status_update();
710 else if (battery_percent < 8) {
711 /* If battery is low, observe voltage during disk activity.
712 * Shut down if voltage drops below shutoff level and we are not
713 * using NiMH or Alkaline batteries.
715 battery_millivolts = (battery_adc_voltage() +
716 battery_millivolts + 1) / 2;
718 /* update battery status every time an update is available */
719 battery_status_update();
721 #ifndef NO_LOW_BATTERY_SHUTDOWN
722 if (!shutdown_timeout &&
723 (battery_millivolts < battery_level_shutoff[battery_type]))
724 sys_poweroff();
725 else
726 #endif
727 avgbat += battery_millivolts - (avgbat / BATT_AVE_SAMPLES);
730 #if CONFIG_CHARGING == CHARGING_CONTROL
731 if (ata_disk_is_active()) {
732 /* flag hdd use for charging calculation */
733 disk_activity_last_cycle = true;
735 #endif
736 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
738 * If we have a lot of pending writes or if the disk is spining,
739 * fsync the debug log file.
741 if((wrcount > 10) || ((wrcount > 0) && ata_disk_is_active())) {
742 fsync(fd);
743 wrcount = 0;
745 #endif
751 * This power thread maintains a history of battery voltage
752 * and implements a charging algorithm.
753 * For a complete description of the charging algorithm read
754 * docs/CHARGING_ALGORITHM.
757 static void power_thread(void)
759 #if CONFIG_CHARGING == CHARGING_CONTROL
760 int i;
761 unsigned int target_voltage = TRICKLE_VOLTAGE; /* desired topoff/trickle
762 * voltage level */
763 int charge_max_time_idle = 0; /* max. charging duration, calculated at
764 * beginning of charging */
765 int charge_max_time_now = 0; /* max. charging duration including
766 * hdd activity */
767 int minutes_disk_activity = 0; /* count minutes of hdd use during
768 * charging */
769 int last_disk_activity = CHARGE_END_LONGD + 1; /* last hdd use x mins ago */
770 #endif
772 /* initialize the voltages for the exponential filter */
773 avgbat = battery_adc_voltage() + 15;
775 #ifndef HAVE_MMC /* this adjustment is only needed for HD based */
776 /* The battery voltage is usually a little lower directly after
777 turning on, because the disk was used heavily. Raise it by 5% */
778 #ifdef HAVE_CHARGING
779 if(!charger_inserted()) /* only if charger not connected */
780 #endif
781 avgbat += (percent_to_volt_discharge[battery_type][6] -
782 percent_to_volt_discharge[battery_type][5]) / 2;
783 #endif /* not HAVE_MMC */
785 avgbat = avgbat * BATT_AVE_SAMPLES;
786 battery_millivolts = avgbat / BATT_AVE_SAMPLES;
788 #if CONFIG_CHARGING
789 if(charger_inserted()) {
790 battery_percent = voltage_to_percent(battery_millivolts,
791 percent_to_volt_charge);
792 #if defined(IRIVER_H100_SERIES) || defined(IRIVER_H300_SERIES)
793 /* Checking for iriver is a temporary kludge. */
794 charger_input_state = CHARGER;
795 #endif
796 } else
797 #endif
798 { battery_percent = voltage_to_percent(battery_millivolts,
799 percent_to_volt_discharge[battery_type]);
800 battery_percent += (battery_percent < 100);
803 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
804 fd = -1;
805 wrcount = 0;
806 #endif
808 while (1)
810 /* rotate the power history */
811 memmove(power_history + 1, power_history,
812 sizeof(power_history) - sizeof(power_history[0]));
814 /* insert new value at the start, in millivolts 8-) */
815 power_history[0] = battery_millivolts;
817 #if CONFIG_CHARGING == CHARGING_CONTROL
818 if (charger_input_state == CHARGER_PLUGGED) {
819 pid_p = 0;
820 pid_i = 0;
821 snprintf(power_message, POWER_MESSAGE_LEN, "Charger plugged in");
823 * The charger was just plugged in. If the battery level is
824 * nearly charged, just trickle. If the battery is low, start
825 * a full charge cycle. If the battery level is in between,
826 * top-off and then trickle.
828 if(battery_percent > START_TOPOFF_CHG) {
829 powermgmt_last_cycle_level = battery_percent;
830 powermgmt_last_cycle_startstop_min = 0;
831 if(battery_percent >= START_TRICKLE_CHG) {
832 charge_state = TRICKLE;
833 target_voltage = TRICKLE_VOLTAGE;
834 } else {
835 charge_state = TOPOFF;
836 target_voltage = TOPOFF_VOLTAGE;
838 } else {
840 * Start the charger full strength
842 i = CHARGE_MAX_TIME_1500 * battery_capacity / 1500;
843 charge_max_time_idle =
844 i * (100 + 35 - battery_percent) / 100;
845 if (charge_max_time_idle > i) {
846 charge_max_time_idle = i;
848 charge_max_time_now = charge_max_time_idle;
850 snprintf(power_message, POWER_MESSAGE_LEN,
851 "ChgAt %d%% max %dm", battery_level(),
852 charge_max_time_now);
854 /* enable the charger after the max time calc is done,
855 because battery_level depends on if the charger is
856 on */
857 DEBUGF("power: charger inserted and battery"
858 " not full, charging\n");
859 powermgmt_last_cycle_level = battery_percent;
860 powermgmt_last_cycle_startstop_min = 0;
861 trickle_sec = 60;
862 long_delta = short_delta = 999999;
863 charge_state = CHARGING;
866 if (charge_state == CHARGING) {
867 /* alter charge time max length with extra disk use */
868 if (disk_activity_last_cycle) {
869 minutes_disk_activity++;
870 charge_max_time_now = charge_max_time_idle +
871 (minutes_disk_activity * 2 / 5);
872 disk_activity_last_cycle = false;
873 last_disk_activity = 0;
874 } else {
875 last_disk_activity++;
878 * Check the delta voltage over the last X minutes so we can do
879 * our end-of-charge logic based on the battery level change.
880 *(no longer use minimum time as logic for charge end has 50
881 * minutes minimum charge built in)
883 if (powermgmt_last_cycle_startstop_min > CHARGE_END_SHORTD) {
884 short_delta = power_history[0] -
885 power_history[CHARGE_END_SHORTD - 1];
888 if (powermgmt_last_cycle_startstop_min > CHARGE_END_LONGD) {
890 * Scan the history: the points where measurement is taken need to
891 * be fairly static. (check prior to short delta 'area')
892 * (also only check first and last 10 cycles - delta in middle OK)
894 long_delta = power_history[0] -
895 power_history[CHARGE_END_LONGD - 1];
897 for(i = CHARGE_END_SHORTD; i < CHARGE_END_SHORTD + 10; i++) {
898 if(((power_history[i] - power_history[i+1]) > 50) ||
899 ((power_history[i] - power_history[i+1]) < -50)) {
900 long_delta = 777777;
901 break;
904 for(i = CHARGE_END_LONGD - 11; i < CHARGE_END_LONGD - 1 ; i++) {
905 if(((power_history[i] - power_history[i+1]) > 50) ||
906 ((power_history[i] - power_history[i+1]) < -50)) {
907 long_delta = 888888;
908 break;
913 snprintf(power_message, POWER_MESSAGE_LEN,
914 "Chg %dm, max %dm", powermgmt_last_cycle_startstop_min,
915 charge_max_time_now);
917 * End of charge criteria (any qualify):
918 * 1) Charged a long time
919 * 2) DeltaV went negative for a short time ( & long delta static)
920 * 3) DeltaV was negative over a longer period (no disk use only)
921 * Note: short_delta and long_delta are millivolts
923 if ((powermgmt_last_cycle_startstop_min >= charge_max_time_now) ||
924 (short_delta <= -50 && long_delta < 50 ) || (long_delta < -20 &&
925 last_disk_activity > CHARGE_END_LONGD)) {
926 if (powermgmt_last_cycle_startstop_min > charge_max_time_now) {
927 DEBUGF("power: powermgmt_last_cycle_startstop_min > charge_max_time_now, "
928 "enough!\n");
930 *have charged too long and deltaV detection did not
931 *work!
933 snprintf(power_message, POWER_MESSAGE_LEN,
934 "Chg tmout %d min", charge_max_time_now);
936 * Switch to trickle charging. We skip the top-off
937 * since we've effectively done the top-off operation
938 * already since we charged for the maximum full
939 * charge time.
941 powermgmt_last_cycle_level = battery_percent;
942 powermgmt_last_cycle_startstop_min = 0;
943 charge_state = TRICKLE;
946 * set trickle charge target to a relative voltage instead
947 * of an arbitrary value - the fully charged voltage may
948 * vary according to ambient temp, battery condition etc
949 * trickle target is -0.15v from full voltage acheived
950 * topup target is -0.05v from full voltage
952 target_voltage = power_history[0] - 150;
954 } else {
955 if(short_delta <= -5) {
956 DEBUGF("power: short-term negative"
957 " delta, enough!\n");
958 snprintf(power_message, POWER_MESSAGE_LEN,
959 "end negd %d %dmin", short_delta,
960 powermgmt_last_cycle_startstop_min);
961 target_voltage = power_history[CHARGE_END_SHORTD - 1]
962 - 50;
963 } else {
964 DEBUGF("power: long-term small "
965 "positive delta, enough!\n");
966 snprintf(power_message, POWER_MESSAGE_LEN,
967 "end lowd %d %dmin", long_delta,
968 powermgmt_last_cycle_startstop_min);
969 target_voltage = power_history[CHARGE_END_LONGD - 1]
970 - 50;
973 * Switch to top-off charging.
975 powermgmt_last_cycle_level = battery_percent;
976 powermgmt_last_cycle_startstop_min = 0;
977 charge_state = TOPOFF;
981 else if (charge_state != DISCHARGING) /* top off or trickle */
984 *Time to switch from topoff to trickle?
986 if ((charge_state == TOPOFF) &&
987 (powermgmt_last_cycle_startstop_min > TOPOFF_MAX_TIME))
989 powermgmt_last_cycle_level = battery_percent;
990 powermgmt_last_cycle_startstop_min = 0;
991 charge_state = TRICKLE;
992 target_voltage = target_voltage - 100;
995 * Adjust trickle charge time (proportional and integral terms).
996 * Note: I considered setting the level higher if the USB is
997 * plugged in, but it doesn't appear to be necessary and will
998 * generate more heat [gvb].
1001 pid_p = ((signed)target_voltage - (signed)battery_millivolts) / 5;
1002 if((pid_p <= PID_DEADZONE) && (pid_p >= -PID_DEADZONE))
1003 pid_p = 0;
1005 if((unsigned) battery_millivolts < target_voltage) {
1006 if(pid_i < 60) {
1007 pid_i++; /* limit so it doesn't "wind up" */
1009 } else {
1010 if(pid_i > 0) {
1011 pid_i--; /* limit so it doesn't "wind up" */
1015 trickle_sec = pid_p + pid_i;
1017 if(trickle_sec > 60) {
1018 trickle_sec = 60;
1020 if(trickle_sec < 0) {
1021 trickle_sec = 0;
1024 } else if (charge_state == DISCHARGING) {
1025 trickle_sec = 0;
1027 * The charger is enabled here only in one case: if it was
1028 * turned on at boot time (power_init). Turn it off now.
1030 if (charger_enabled)
1031 charger_enable(false);
1034 if (charger_input_state == CHARGER_UNPLUGGED) {
1036 * The charger was just unplugged.
1038 DEBUGF("power: charger disconnected, disabling\n");
1040 charger_enable(false);
1041 powermgmt_last_cycle_level = battery_percent;
1042 powermgmt_last_cycle_startstop_min = 0;
1043 trickle_sec = 0;
1044 pid_p = 0;
1045 pid_i = 0;
1046 charge_state = DISCHARGING;
1047 snprintf(power_message, POWER_MESSAGE_LEN, "Charger: discharge");
1050 #endif /* CONFIG_CHARGING == CHARGING_CONTROL */
1052 /* sleep for a minute */
1054 #if CONFIG_CHARGING == CHARGING_CONTROL
1055 if(trickle_sec > 0) {
1056 charger_enable(true);
1057 power_thread_sleep(HZ * trickle_sec);
1059 if(trickle_sec < 60)
1060 charger_enable(false);
1061 power_thread_sleep(HZ * (60 - trickle_sec));
1062 #else
1063 power_thread_sleep(HZ * 60);
1064 #endif
1066 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1067 if(usb_inserted()) {
1068 if(fd >= 0) {
1069 /* It is probably too late to close the file but we can try...*/
1070 close(fd);
1071 fd = -1;
1073 } else {
1074 if(fd < 0) {
1075 fd = open(DEBUG_FILE_NAME, O_WRONLY | O_APPEND | O_CREAT);
1076 if(fd >= 0) {
1077 snprintf(debug_message, DEBUG_MESSAGE_LEN,
1078 "cycle_min, bat_millivolts, bat_percent, chgr_state, charge_state, pid_p, pid_i, trickle_sec\n");
1079 write(fd, debug_message, strlen(debug_message));
1080 wrcount = 99; /* force a flush */
1083 if(fd >= 0) {
1084 snprintf(debug_message, DEBUG_MESSAGE_LEN,
1085 "%d, %d, %d, %d, %d, %d, %d, %d\n",
1086 powermgmt_last_cycle_startstop_min, battery_millivolts,
1087 battery_percent, charger_input_state, charge_state,
1088 pid_p, pid_i, trickle_sec);
1089 write(fd, debug_message, strlen(debug_message));
1090 wrcount++;
1093 #endif
1094 handle_auto_poweroff();
1096 #if CONFIG_CHARGING == CHARGING_CONTROL
1097 powermgmt_last_cycle_startstop_min++;
1098 #endif
1102 void powermgmt_init(void)
1104 /* init history to 0 */
1105 memset(power_history, 0x00, sizeof(power_history));
1106 create_thread(power_thread, power_stack, sizeof(power_stack), 0,
1107 power_thread_name IF_PRIO(, PRIORITY_SYSTEM)
1108 IF_COP(, CPU));
1111 #endif /* SIMULATOR */
1113 void sys_poweroff(void)
1115 logf("sys_poweroff()");
1116 /* If the main thread fails to shut down the system, we will force a
1117 power off after an 20 second timeout - 28 seconds if recording */
1118 if (shutdown_timeout == 0)
1120 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1121 pcf50606_reset_timeout(); /* Reset timer on first attempt only */
1122 #endif
1123 #ifdef HAVE_RECORDING
1124 if (audio_status() & AUDIO_STATUS_RECORD)
1125 shutdown_timeout += HZ*8;
1126 #endif
1127 shutdown_timeout += HZ*20;
1130 queue_broadcast(SYS_POWEROFF, 0);
1133 void cancel_shutdown(void)
1135 logf("sys_cancel_shutdown()");
1137 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1138 /* TODO: Move some things to target/ tree */
1139 if (shutdown_timeout)
1140 pcf50606_reset_timeout();
1141 #endif
1143 shutdown_timeout = 0;
1146 /* Various hardware housekeeping tasks relating to shutting down the jukebox */
1147 void shutdown_hw(void)
1149 #ifndef SIMULATOR
1150 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1151 if(fd >= 0) {
1152 close(fd);
1153 fd = -1;
1155 #endif
1156 audio_stop();
1157 if (battery_level_safe()) { /* do not save on critical battery */
1158 #ifdef HAVE_LCD_BITMAP
1159 glyph_cache_save();
1160 #endif
1161 if(ata_disk_is_active())
1162 ata_spindown(1);
1164 while(ata_disk_is_active())
1165 sleep(HZ/10);
1167 #if CONFIG_CODEC != SWCODEC
1168 mp3_shutdown();
1169 #else
1170 audiohw_close();
1171 #endif
1173 /* If HD is still active we try to wait for spindown, otherwise the
1174 shutdown_timeout in power_thread_sleep will force a power off */
1175 while(ata_disk_is_active())
1176 sleep(HZ/10);
1177 #ifndef IAUDIO_X5
1178 lcd_set_contrast(0);
1179 #endif /* IAUDIO_X5 */
1180 #ifdef HAVE_REMOTE_LCD
1181 lcd_remote_set_contrast(0);
1182 #endif
1184 #ifdef HAVE_LCD_SHUTDOWN
1185 lcd_shutdown();
1186 #endif
1188 /* Small delay to make sure all HW gets time to flush. Especially
1189 eeprom chips are quite slow and might be still writing the last
1190 byte. */
1191 sleep(HZ/4);
1192 power_off();
1193 #endif /* #ifndef SIMULATOR */