add global proxy / cache settings to httpget class. This removes the need of passing...
[Rockbox.git] / firmware / powermgmt.c
blobd1efa29dcaada12c9b8a7b3239b6cdc3b6ce6b48
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 static void send_battery_level_event(void);
84 static int last_sent_battery_level = 100;
86 #if CONFIG_CHARGING
87 charger_input_state_type charger_input_state IDATA_ATTR;
88 #endif
90 #ifdef SIMULATOR /***********************************************************/
92 #define BATT_MINMVOLT 2500 /* minimum millivolts of battery */
93 #define BATT_MAXMVOLT 4500 /* maximum millivolts of battery */
94 #define BATT_MAXRUNTIME (10 * 60) /* maximum runtime with full battery in minutes */
96 static unsigned int battery_millivolts = (unsigned int)BATT_MAXMVOLT;
97 static int battery_percent = 100; /* battery capacity level in percent */
98 static int powermgmt_est_runningtime_min = BATT_MAXRUNTIME; /* estimated remaining time in minutes */
100 static void battery_status_update(void)
102 static time_t last_change = 0;
103 static bool charging = false;
104 time_t now;
106 time(&now);
107 if (last_change < now)
109 last_change = now;
111 /* change the values: */
112 if (charging)
114 if (battery_millivolts >= BATT_MAXMVOLT)
116 /* Pretend the charger was disconnected */
117 charging = false;
118 queue_broadcast(SYS_CHARGER_DISCONNECTED, 0);
119 last_sent_battery_level = 100;
122 else
124 if (battery_millivolts <= BATT_MINMVOLT)
126 /* Pretend the charger was connected */
127 charging = true;
128 queue_broadcast(SYS_CHARGER_CONNECTED, 0);
129 last_sent_battery_level = 0;
132 if (charging)
133 battery_millivolts += (BATT_MAXMVOLT - BATT_MINMVOLT) / 50;
134 else
135 battery_millivolts -= (BATT_MAXMVOLT - BATT_MINMVOLT) / 100;
137 battery_percent = 100 * (battery_millivolts - BATT_MINMVOLT) / (BATT_MAXMVOLT - BATT_MINMVOLT);
138 powermgmt_est_runningtime_min = battery_percent * BATT_MAXRUNTIME / 100;
140 send_battery_level_event();
143 void battery_read_info(int *voltage, int *level)
145 battery_status_update();
147 if (voltage)
148 *voltage = battery_millivolts;
150 if (level)
151 *level = battery_percent;
154 unsigned int battery_voltage(void)
156 battery_status_update();
157 return battery_millivolts;
160 int battery_level(void)
162 battery_status_update();
163 return battery_percent;
166 int battery_time(void)
168 battery_status_update();
169 return powermgmt_est_runningtime_min;
172 bool battery_level_safe(void)
174 return battery_level() >= 10;
177 void set_poweroff_timeout(int timeout)
179 (void)timeout;
182 void set_battery_capacity(int capacity)
184 (void)capacity;
187 #if BATTERY_TYPES_COUNT > 1
188 void set_battery_type(int type)
190 (void)type;
192 #endif
194 void reset_poweroff_timer(void)
198 #else /* not SIMULATOR ******************************************************/
200 #if CONFIG_CHARGING == CHARGING_CONTROL
201 int long_delta; /* long term delta battery voltage */
202 int short_delta; /* short term delta battery voltage */
203 bool disk_activity_last_cycle = false; /* flag set to aid charger time
204 * calculation */
205 char power_message[POWER_MESSAGE_LEN] = ""; /* message that's shown in
206 debug menu */
207 /* percentage at which charging
208 starts */
209 int powermgmt_last_cycle_startstop_min = 0; /* how many minutes ago was the
210 charging started or
211 stopped? */
212 int powermgmt_last_cycle_level = 0; /* which level had the
213 batteries at this time? */
214 int trickle_sec = 0; /* how many seconds should the
215 charger be enabled per
216 minute for trickle
217 charging? */
218 int pid_p = 0; /* PID proportional term */
219 int pid_i = 0; /* PID integral term */
220 #endif /* CONFIG_CHARGING == CHARGING_CONTROL */
223 * Average battery voltage and charger voltage, filtered via a digital
224 * exponential filter.
226 static unsigned int avgbat; /* average battery voltage (filtering) */
227 static unsigned int battery_millivolts;/* filtered battery voltage, millivolts */
229 #ifdef HAVE_CHARGE_CTRL
230 #define BATT_AVE_SAMPLES 32 /* filter constant / @ 2Hz sample rate */
231 #else
232 #define BATT_AVE_SAMPLES 128 /* slw filter constant for all others */
233 #endif
235 /* battery level (0-100%) of this minute, updated once per minute */
236 static int battery_percent = -1;
237 static int battery_capacity = BATTERY_CAPACITY_DEFAULT; /* default value, mAh */
238 #if BATTERY_TYPES_COUNT > 1
239 static int battery_type = 0;
240 #else
241 #define battery_type 0
242 #endif
244 /* Power history: power_history[0] is the newest sample */
245 unsigned short power_history[POWER_HISTORY_LEN];
247 static char power_stack[DEFAULT_STACK_SIZE/2 + DEBUG_STACK];
248 static const char power_thread_name[] = "power";
250 static int poweroff_timeout = 0;
251 static int powermgmt_est_runningtime_min = -1;
253 static bool sleeptimer_active = false;
254 static long sleeptimer_endtick;
256 static long last_event_tick;
258 static int voltage_to_battery_level(int battery_millivolts);
259 static void battery_status_update(void);
260 static int runcurrent(void);
262 void battery_read_info(int *voltage, int *level)
264 int millivolts = battery_adc_voltage();
266 if (voltage)
267 *voltage = millivolts;
269 if (level)
270 *level = voltage_to_battery_level(millivolts);
273 void reset_poweroff_timer(void)
275 last_event_tick = current_tick;
278 #if BATTERY_TYPES_COUNT > 1
279 void set_battery_type(int type)
281 if (type != battery_type) {
282 battery_type = type;
283 battery_status_update(); /* recalculate the battery status */
286 #endif
288 void set_battery_capacity(int capacity)
290 battery_capacity = capacity;
291 if (battery_capacity > BATTERY_CAPACITY_MAX)
292 battery_capacity = BATTERY_CAPACITY_MAX;
293 if (battery_capacity < BATTERY_CAPACITY_MIN)
294 battery_capacity = BATTERY_CAPACITY_MIN;
295 battery_status_update(); /* recalculate the battery status */
298 int battery_time(void)
300 return powermgmt_est_runningtime_min;
303 /* Returns battery level in percent */
304 int battery_level(void)
306 return battery_percent;
309 /* Returns filtered battery voltage [millivolts] */
310 unsigned int battery_voltage(void)
312 return battery_millivolts;
315 /* Tells if the battery level is safe for disk writes */
316 bool battery_level_safe(void)
318 return battery_millivolts > battery_level_dangerous[battery_type];
321 void set_poweroff_timeout(int timeout)
323 poweroff_timeout = timeout;
326 void set_sleep_timer(int seconds)
328 if(seconds) {
329 sleeptimer_active = true;
330 sleeptimer_endtick = current_tick + seconds * HZ;
332 else {
333 sleeptimer_active = false;
334 sleeptimer_endtick = 0;
338 int get_sleep_timer(void)
340 if(sleeptimer_active)
341 return (sleeptimer_endtick - current_tick) / HZ;
342 else
343 return 0;
346 /* look into the percent_to_volt_* table and get a realistic battery level */
347 static int voltage_to_percent(int voltage, const short* table)
349 if (voltage <= table[0])
350 return 0;
351 else
352 if (voltage >= table[10])
353 return 100;
354 else {
355 /* search nearest value */
356 int i = 0;
357 while ((i < 10) && (table[i+1] < voltage))
358 i++;
359 /* interpolate linear between the smaller and greater value */
360 return (i * 10) /* Tens digit, 10% per entry */
361 + (((voltage - table[i]) * 10)
362 / (table[i+1] - table[i])); /* Ones digit: interpolated */
366 /* update battery level and estimated runtime, called once per minute or
367 * when battery capacity / type settings are changed */
368 static int voltage_to_battery_level(int battery_millivolts)
370 int level;
372 #if defined(CONFIG_CHARGER) \
373 && (defined(IRIVER_H100_SERIES) || defined(IRIVER_H300_SERIES))
374 /* Checking for iriver is a temporary kludge.
375 * This code needs rework/unification */
376 if (charger_input_state == NO_CHARGER) {
377 /* discharging. calculate new battery level and average with last */
378 level = voltage_to_percent(battery_millivolts,
379 percent_to_volt_discharge[battery_type]);
380 if (level != (battery_percent - 1))
381 level = (level + battery_percent + 1) / 2;
383 else if (charger_input_state == CHARGER_UNPLUGGED) {
384 /* just unplugged. adjust filtered values */
385 battery_millivolts -= percent_to_volt_charge[battery_percent/10] -
386 percent_to_volt_discharge[0][battery_percent/10];
387 avgbat = battery_millivolts * 1000 * BATT_AVE_SAMPLES;
388 level = battery_percent;
390 else if (charger_input_state == CHARGER_PLUGGED) {
391 /* just plugged in. adjust battery values */
392 battery_millivolts += percent_to_volt_charge[battery_percent/10] -
393 percent_to_volt_discharge[0][battery_percent/10];
394 avgbat = battery_millivolts * 1000 * BATT_AVE_SAMPLES;
395 level = MIN(12 * battery_percent / 10, 99);
397 else { /* charging. calculate new battery level */
398 level = voltage_to_percent(battery_millivolts,
399 percent_to_volt_charge);
401 #elif CONFIG_CHARGING >= CHARGING_MONITOR
402 if (charge_state == DISCHARGING) {
403 level = voltage_to_percent(battery_millivolts,
404 percent_to_volt_discharge[battery_type]);
406 else if (charge_state == CHARGING) {
407 /* battery level is defined to be < 100% until charging is finished */
408 level = MIN(voltage_to_percent(battery_millivolts,
409 percent_to_volt_charge), 99);
411 else { /* in topoff/trickle charge, battery is by definition 100% full */
412 level = 100;
414 #else
415 /* always use the discharge table */
416 level = voltage_to_percent(battery_millivolts,
417 percent_to_volt_discharge[battery_type]);
418 #endif
420 return level;
423 static void battery_status_update(void)
425 int level = voltage_to_battery_level(battery_millivolts);
427 /* calculate estimated remaining running time */
428 /* discharging: remaining running time */
429 /* charging: remaining charging time */
430 #if CONFIG_CHARGING >= CHARGING_MONITOR
431 if (charge_state == CHARGING) {
432 powermgmt_est_runningtime_min = (100 - level) * battery_capacity * 60
433 / 100 / (CURRENT_MAX_CHG - runcurrent());
435 else
436 #elif CONFIG_CHARGING \
437 && (defined(IRIVER_H100_SERIES) || defined(IRIVER_H300_SERIES))
438 /* Checking for iriver is a temporary kludge.
439 * This code needs rework/unification */
440 if (charger_inserted()) {
441 #ifdef IRIVER_H300_SERIES
442 /* H300_SERIES use CURRENT_MAX_CHG for basic charge time (80%)
443 * plus 110 min top off charge time */
444 powermgmt_est_runningtime_min = ((100-level) * battery_capacity * 80
445 /100 / CURRENT_MAX_CHG) + 110;
446 #else
447 /* H100_SERIES scaled for 160 min basic charge time (80%) on
448 * 1600 mAh battery plus 110 min top off charge time */
449 powermgmt_est_runningtime_min = ((100 - level) * battery_capacity
450 / 993) + 110;
451 #endif
452 level = (level * 80) / 100;
453 if (level > 72) { /* > 91% */
454 int i = POWER_HISTORY_LEN;
455 int d = 1;
456 #ifdef HAVE_CHARGE_STATE
457 if (charge_state == DISCHARGING)
458 d = -2;
459 #endif
460 while ((i > 2) && (d > 0)) /* search zero or neg. delta */
461 d = power_history[0] - power_history[--i];
462 if ((((d == 0) && (i > 6)) || (d == -1)) && (i < 118)) {
463 /* top off charging */
464 level = MIN(80 + (i*19 / 113), 99); /* show 81% .. 99% */
465 powermgmt_est_runningtime_min = MAX(116 - i, 0);
467 else if ((d < 0) || (i > 117)) {
468 /* charging finished */
469 level = 100;
470 powermgmt_est_runningtime_min = battery_capacity * 60
471 / runcurrent();
475 else
476 #endif /* BATT_LIPOL1300 */
478 if ((battery_millivolts + 20) > percent_to_volt_discharge[0][0])
479 powermgmt_est_runningtime_min = (level + battery_percent) * 60 *
480 battery_capacity / 200 / runcurrent();
481 else
482 powermgmt_est_runningtime_min = (battery_millivolts -
483 battery_level_shutoff[0]) / 2;
486 battery_percent = level;
487 send_battery_level_event();
491 * We shut off in the following cases:
492 * 1) The unit is idle, not playing music
493 * 2) The unit is playing music, but is paused
494 * 3) The battery level has reached shutdown limit
496 * We do not shut off in the following cases:
497 * 1) The USB is connected
498 * 2) The charger is connected
499 * 3) We are recording, or recording with pause
500 * 4) The radio is playing
502 static void handle_auto_poweroff(void)
504 long timeout = poweroff_timeout*60*HZ;
505 int audio_stat = audio_status();
507 #if CONFIG_CHARGING
509 * Inhibit shutdown as long as the charger is plugged in. If it is
510 * unplugged, wait for a timeout period and then shut down.
512 if(charger_input_state == CHARGER || audio_stat == AUDIO_STATUS_PLAY) {
513 last_event_tick = current_tick;
515 #endif
517 #ifndef NO_LOW_BATTERY_SHUTDOWN
518 /* switch off unit if battery level is too low for reliable operation */
519 if(battery_millivolts < battery_level_shutoff[battery_type]) {
520 if(!shutdown_timeout) {
521 backlight_on();
522 sys_poweroff();
525 #endif
527 if(timeout &&
528 #if CONFIG_TUNER && !defined(BOOTLOADER)
529 (!(get_radio_status() & FMRADIO_PLAYING)) &&
530 #endif
531 !usb_inserted() &&
532 ((audio_stat == 0) ||
533 ((audio_stat == (AUDIO_STATUS_PLAY | AUDIO_STATUS_PAUSE)) &&
534 !sleeptimer_active)))
536 if(TIME_AFTER(current_tick, last_event_tick + timeout) &&
537 TIME_AFTER(current_tick, last_disk_activity + timeout))
539 sys_poweroff();
542 else
544 /* Handle sleeptimer */
545 if(sleeptimer_active && !usb_inserted())
547 if(TIME_AFTER(current_tick, sleeptimer_endtick))
549 audio_stop();
550 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
551 if((charger_input_state == CHARGER) ||
552 (charger_input_state == CHARGER_PLUGGED))
554 DEBUGF("Sleep timer timeout. Stopping...\n");
555 set_sleep_timer(0);
556 backlight_off(); /* Nighty, nighty... */
558 else
559 #endif
561 DEBUGF("Sleep timer timeout. Shutting off...\n");
562 sys_poweroff();
570 * Estimate how much current we are drawing just to run.
572 static int runcurrent(void)
574 int current;
576 #if MEM == 8 && !defined(HAVE_MMC)
577 /* assuming 192 kbps, the running time is 22% longer with 8MB */
578 current = (CURRENT_NORMAL*100/122);
579 #else
580 current = CURRENT_NORMAL;
581 #endif /* MEM == 8 */
583 if(usb_inserted()
584 #if defined(HAVE_USB_POWER)
585 #if (CURRENT_USB < CURRENT_NORMAL)
586 || usb_powered()
587 #else
588 && !usb_powered()
589 #endif
590 #endif
593 current = CURRENT_USB;
596 #if defined(HAVE_BACKLIGHT) && !defined(BOOTLOADER)
597 if (backlight_get_current_timeout() == 0) /* LED always on */
598 current += CURRENT_BACKLIGHT;
599 #endif
601 #if defined(HAVE_RECORDING) && defined(CURRENT_RECORD)
602 if (audio_status() & AUDIO_STATUS_RECORD)
603 current += CURRENT_RECORD;
604 #endif
606 #ifdef HAVE_SPDIF_POWER
607 if (spdif_powered())
608 current += CURRENT_SPDIF_OUT;
609 #endif
611 #ifdef HAVE_REMOTE_LCD
612 if (remote_detect())
613 current += CURRENT_REMOTE;
614 #endif
616 return(current);
620 /* Check to see whether or not we've received an alarm in the last second */
621 #ifdef HAVE_RTC_ALARM
622 static void power_thread_rtc_process(void)
624 if (rtc_check_alarm_flag()) {
625 rtc_enable_alarm(false);
628 #endif
631 * This function is called to do the relativly long sleep waits from within the
632 * main power_thread loop while at the same time servicing any other periodic
633 * functions in the power thread which need to be called at a faster periodic
634 * rate than the slow periodic rate of the main power_thread loop.
636 * While we are waiting for the time to expire, we average the battery
637 * voltages.
639 static void power_thread_sleep(int ticks)
641 int small_ticks;
643 while (ticks > 0) {
645 #if CONFIG_CHARGING
647 * Detect charger plugged/unplugged transitions. On a plugged or
648 * unplugged event, we return immediately, run once through the main
649 * loop (including the subroutines), and end up back here where we
650 * transition to the appropriate steady state charger on/off state.
652 if(charger_inserted()
653 #ifdef HAVE_USB_POWER /* USB powered or USB inserted both provide power */
654 || usb_powered()
655 #if CONFIG_CHARGING
656 || (usb_inserted() && usb_charging_enabled())
657 #endif
658 #endif
660 switch(charger_input_state) {
661 case NO_CHARGER:
662 case CHARGER_UNPLUGGED:
663 charger_input_state = CHARGER_PLUGGED;
664 return;
665 case CHARGER_PLUGGED:
666 queue_broadcast(SYS_CHARGER_CONNECTED, 0);
667 last_sent_battery_level = 0;
668 charger_input_state = CHARGER;
669 break;
670 case CHARGER:
671 break;
673 } else { /* charger not inserted */
674 switch(charger_input_state) {
675 case NO_CHARGER:
676 break;
677 case CHARGER_UNPLUGGED:
678 queue_broadcast(SYS_CHARGER_DISCONNECTED, 0);
679 last_sent_battery_level = 100;
680 charger_input_state = NO_CHARGER;
681 break;
682 case CHARGER_PLUGGED:
683 case CHARGER:
684 charger_input_state = CHARGER_UNPLUGGED;
685 return;
688 #endif
689 #if CONFIG_CHARGING == CHARGING_MONITOR
690 switch (charger_input_state) {
691 case CHARGER_UNPLUGGED:
692 case NO_CHARGER:
693 charge_state = DISCHARGING;
694 break;
695 case CHARGER_PLUGGED:
696 case CHARGER:
697 if (charging_state()) {
698 charge_state = CHARGING;
699 } else {
700 charge_state = DISCHARGING;
702 break;
705 #endif /* CONFIG_CHARGING == CHARGING_MONITOR */
707 small_ticks = MIN(HZ/2, ticks);
708 sleep(small_ticks);
709 ticks -= small_ticks;
711 /* If the power off timeout expires, the main thread has failed
712 to shut down the system, and we need to force a power off */
713 if(shutdown_timeout) {
714 shutdown_timeout -= small_ticks;
715 if(shutdown_timeout <= 0)
716 power_off();
719 #ifdef HAVE_RTC_ALARM
720 power_thread_rtc_process();
721 #endif
724 * Do a digital exponential filter. We don't sample the battery if
725 * the disk is spinning unless we are in USB mode (the disk will most
726 * likely always be spinning in USB mode).
728 if (!ata_disk_is_active() || usb_inserted()) {
729 avgbat += battery_adc_voltage() - (avgbat / BATT_AVE_SAMPLES);
731 * battery_millivolts is the millivolt-scaled filtered battery value.
733 battery_millivolts = avgbat / BATT_AVE_SAMPLES;
735 /* update battery status every time an update is available */
736 battery_status_update();
738 else if (battery_percent < 8) {
739 /* If battery is low, observe voltage during disk activity.
740 * Shut down if voltage drops below shutoff level and we are not
741 * using NiMH or Alkaline batteries.
743 battery_millivolts = (battery_adc_voltage() +
744 battery_millivolts + 1) / 2;
746 /* update battery status every time an update is available */
747 battery_status_update();
749 #ifndef NO_LOW_BATTERY_SHUTDOWN
750 if (!shutdown_timeout &&
751 (battery_millivolts < battery_level_shutoff[battery_type]))
752 sys_poweroff();
753 else
754 #endif
755 avgbat += battery_millivolts - (avgbat / BATT_AVE_SAMPLES);
758 #if CONFIG_CHARGING == CHARGING_CONTROL
759 if (ata_disk_is_active()) {
760 /* flag hdd use for charging calculation */
761 disk_activity_last_cycle = true;
763 #endif
764 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
766 * If we have a lot of pending writes or if the disk is spining,
767 * fsync the debug log file.
769 if((wrcount > 10) || ((wrcount > 0) && ata_disk_is_active())) {
770 fsync(fd);
771 wrcount = 0;
773 #endif
779 * This power thread maintains a history of battery voltage
780 * and implements a charging algorithm.
781 * For a complete description of the charging algorithm read
782 * docs/CHARGING_ALGORITHM.
785 static void power_thread(void)
787 #if CONFIG_CHARGING == CHARGING_CONTROL
788 int i;
789 unsigned int target_voltage = TRICKLE_VOLTAGE; /* desired topoff/trickle
790 * voltage level */
791 int charge_max_time_idle = 0; /* max. charging duration, calculated at
792 * beginning of charging */
793 int charge_max_time_now = 0; /* max. charging duration including
794 * hdd activity */
795 int minutes_disk_activity = 0; /* count minutes of hdd use during
796 * charging */
797 int last_disk_activity = CHARGE_END_LONGD + 1; /* last hdd use x mins ago */
798 #endif
800 /* Delay reading the first battery level */
801 sleep(HZ/100);
803 /* initialize the voltages for the exponential filter */
804 avgbat = battery_adc_voltage() + 15;
806 #ifndef HAVE_MMC /* this adjustment is only needed for HD based */
807 /* The battery voltage is usually a little lower directly after
808 turning on, because the disk was used heavily. Raise it by 5% */
809 #ifdef HAVE_CHARGING
810 if(!charger_inserted()) /* only if charger not connected */
811 #endif
812 avgbat += (percent_to_volt_discharge[battery_type][6] -
813 percent_to_volt_discharge[battery_type][5]) / 2;
814 #endif /* not HAVE_MMC */
816 avgbat = avgbat * BATT_AVE_SAMPLES;
817 battery_millivolts = avgbat / BATT_AVE_SAMPLES;
819 #if CONFIG_CHARGING
820 if(charger_inserted()) {
821 battery_percent = voltage_to_percent(battery_millivolts,
822 percent_to_volt_charge);
823 #if defined(IRIVER_H100_SERIES) || defined(IRIVER_H300_SERIES)
824 /* Checking for iriver is a temporary kludge. */
825 charger_input_state = CHARGER;
826 #endif
827 } else
828 #endif
829 { battery_percent = voltage_to_percent(battery_millivolts,
830 percent_to_volt_discharge[battery_type]);
831 battery_percent += (battery_percent < 100);
834 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
835 fd = -1;
836 wrcount = 0;
837 #endif
839 while (1)
841 /* rotate the power history */
842 memmove(power_history + 1, power_history,
843 sizeof(power_history) - sizeof(power_history[0]));
845 /* insert new value at the start, in millivolts 8-) */
846 power_history[0] = battery_millivolts;
848 #if CONFIG_CHARGING == CHARGING_CONTROL
849 if (charger_input_state == CHARGER_PLUGGED) {
850 pid_p = 0;
851 pid_i = 0;
852 snprintf(power_message, POWER_MESSAGE_LEN, "Charger plugged in");
854 * The charger was just plugged in. If the battery level is
855 * nearly charged, just trickle. If the battery is low, start
856 * a full charge cycle. If the battery level is in between,
857 * top-off and then trickle.
859 if(battery_percent > START_TOPOFF_CHG) {
860 powermgmt_last_cycle_level = battery_percent;
861 powermgmt_last_cycle_startstop_min = 0;
862 if(battery_percent >= START_TRICKLE_CHG) {
863 charge_state = TRICKLE;
864 target_voltage = TRICKLE_VOLTAGE;
865 } else {
866 charge_state = TOPOFF;
867 target_voltage = TOPOFF_VOLTAGE;
869 } else {
871 * Start the charger full strength
873 i = CHARGE_MAX_TIME_1500 * battery_capacity / 1500;
874 charge_max_time_idle =
875 i * (100 + 35 - battery_percent) / 100;
876 if (charge_max_time_idle > i) {
877 charge_max_time_idle = i;
879 charge_max_time_now = charge_max_time_idle;
881 snprintf(power_message, POWER_MESSAGE_LEN,
882 "ChgAt %d%% max %dm", battery_level(),
883 charge_max_time_now);
885 /* enable the charger after the max time calc is done,
886 because battery_level depends on if the charger is
887 on */
888 DEBUGF("power: charger inserted and battery"
889 " not full, charging\n");
890 powermgmt_last_cycle_level = battery_percent;
891 powermgmt_last_cycle_startstop_min = 0;
892 trickle_sec = 60;
893 long_delta = short_delta = 999999;
894 charge_state = CHARGING;
897 if (charge_state == CHARGING) {
898 /* alter charge time max length with extra disk use */
899 if (disk_activity_last_cycle) {
900 minutes_disk_activity++;
901 charge_max_time_now = charge_max_time_idle +
902 (minutes_disk_activity * 2 / 5);
903 disk_activity_last_cycle = false;
904 last_disk_activity = 0;
905 } else {
906 last_disk_activity++;
909 * Check the delta voltage over the last X minutes so we can do
910 * our end-of-charge logic based on the battery level change.
911 *(no longer use minimum time as logic for charge end has 50
912 * minutes minimum charge built in)
914 if (powermgmt_last_cycle_startstop_min > CHARGE_END_SHORTD) {
915 short_delta = power_history[0] -
916 power_history[CHARGE_END_SHORTD - 1];
919 if (powermgmt_last_cycle_startstop_min > CHARGE_END_LONGD) {
921 * Scan the history: the points where measurement is taken need to
922 * be fairly static. (check prior to short delta 'area')
923 * (also only check first and last 10 cycles - delta in middle OK)
925 long_delta = power_history[0] -
926 power_history[CHARGE_END_LONGD - 1];
928 for(i = CHARGE_END_SHORTD; i < CHARGE_END_SHORTD + 10; i++) {
929 if(((power_history[i] - power_history[i+1]) > 50) ||
930 ((power_history[i] - power_history[i+1]) < -50)) {
931 long_delta = 777777;
932 break;
935 for(i = CHARGE_END_LONGD - 11; i < CHARGE_END_LONGD - 1 ; i++) {
936 if(((power_history[i] - power_history[i+1]) > 50) ||
937 ((power_history[i] - power_history[i+1]) < -50)) {
938 long_delta = 888888;
939 break;
944 snprintf(power_message, POWER_MESSAGE_LEN,
945 "Chg %dm, max %dm", powermgmt_last_cycle_startstop_min,
946 charge_max_time_now);
948 * End of charge criteria (any qualify):
949 * 1) Charged a long time
950 * 2) DeltaV went negative for a short time ( & long delta static)
951 * 3) DeltaV was negative over a longer period (no disk use only)
952 * Note: short_delta and long_delta are millivolts
954 if ((powermgmt_last_cycle_startstop_min >= charge_max_time_now) ||
955 (short_delta <= -50 && long_delta < 50 ) || (long_delta < -20 &&
956 last_disk_activity > CHARGE_END_LONGD)) {
957 if (powermgmt_last_cycle_startstop_min > charge_max_time_now) {
958 DEBUGF("power: powermgmt_last_cycle_startstop_min > charge_max_time_now, "
959 "enough!\n");
961 *have charged too long and deltaV detection did not
962 *work!
964 snprintf(power_message, POWER_MESSAGE_LEN,
965 "Chg tmout %d min", charge_max_time_now);
967 * Switch to trickle charging. We skip the top-off
968 * since we've effectively done the top-off operation
969 * already since we charged for the maximum full
970 * charge time.
972 powermgmt_last_cycle_level = battery_percent;
973 powermgmt_last_cycle_startstop_min = 0;
974 charge_state = TRICKLE;
977 * set trickle charge target to a relative voltage instead
978 * of an arbitrary value - the fully charged voltage may
979 * vary according to ambient temp, battery condition etc
980 * trickle target is -0.15v from full voltage acheived
981 * topup target is -0.05v from full voltage
983 target_voltage = power_history[0] - 150;
985 } else {
986 if(short_delta <= -5) {
987 DEBUGF("power: short-term negative"
988 " delta, enough!\n");
989 snprintf(power_message, POWER_MESSAGE_LEN,
990 "end negd %d %dmin", short_delta,
991 powermgmt_last_cycle_startstop_min);
992 target_voltage = power_history[CHARGE_END_SHORTD - 1]
993 - 50;
994 } else {
995 DEBUGF("power: long-term small "
996 "positive delta, enough!\n");
997 snprintf(power_message, POWER_MESSAGE_LEN,
998 "end lowd %d %dmin", long_delta,
999 powermgmt_last_cycle_startstop_min);
1000 target_voltage = power_history[CHARGE_END_LONGD - 1]
1001 - 50;
1004 * Switch to top-off charging.
1006 powermgmt_last_cycle_level = battery_percent;
1007 powermgmt_last_cycle_startstop_min = 0;
1008 charge_state = TOPOFF;
1012 else if (charge_state != DISCHARGING) /* top off or trickle */
1015 *Time to switch from topoff to trickle?
1017 if ((charge_state == TOPOFF) &&
1018 (powermgmt_last_cycle_startstop_min > TOPOFF_MAX_TIME))
1020 powermgmt_last_cycle_level = battery_percent;
1021 powermgmt_last_cycle_startstop_min = 0;
1022 charge_state = TRICKLE;
1023 target_voltage = target_voltage - 100;
1026 * Adjust trickle charge time (proportional and integral terms).
1027 * Note: I considered setting the level higher if the USB is
1028 * plugged in, but it doesn't appear to be necessary and will
1029 * generate more heat [gvb].
1032 pid_p = ((signed)target_voltage - (signed)battery_millivolts) / 5;
1033 if((pid_p <= PID_DEADZONE) && (pid_p >= -PID_DEADZONE))
1034 pid_p = 0;
1036 if((unsigned) battery_millivolts < target_voltage) {
1037 if(pid_i < 60) {
1038 pid_i++; /* limit so it doesn't "wind up" */
1040 } else {
1041 if(pid_i > 0) {
1042 pid_i--; /* limit so it doesn't "wind up" */
1046 trickle_sec = pid_p + pid_i;
1048 if(trickle_sec > 60) {
1049 trickle_sec = 60;
1051 if(trickle_sec < 0) {
1052 trickle_sec = 0;
1055 } else if (charge_state == DISCHARGING) {
1056 trickle_sec = 0;
1058 * The charger is enabled here only in one case: if it was
1059 * turned on at boot time (power_init). Turn it off now.
1061 if (charger_enabled)
1062 charger_enable(false);
1065 if (charger_input_state == CHARGER_UNPLUGGED) {
1067 * The charger was just unplugged.
1069 DEBUGF("power: charger disconnected, disabling\n");
1071 charger_enable(false);
1072 powermgmt_last_cycle_level = battery_percent;
1073 powermgmt_last_cycle_startstop_min = 0;
1074 trickle_sec = 0;
1075 pid_p = 0;
1076 pid_i = 0;
1077 charge_state = DISCHARGING;
1078 snprintf(power_message, POWER_MESSAGE_LEN, "Charger: discharge");
1081 #endif /* CONFIG_CHARGING == CHARGING_CONTROL */
1083 /* sleep for a minute */
1085 #if CONFIG_CHARGING == CHARGING_CONTROL
1086 if(trickle_sec > 0) {
1087 charger_enable(true);
1088 power_thread_sleep(HZ * trickle_sec);
1090 if(trickle_sec < 60)
1091 charger_enable(false);
1092 power_thread_sleep(HZ * (60 - trickle_sec));
1093 #else
1094 power_thread_sleep(HZ * 60);
1095 #endif
1097 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1098 if(usb_inserted()) {
1099 if(fd >= 0) {
1100 /* It is probably too late to close the file but we can try...*/
1101 close(fd);
1102 fd = -1;
1104 } else {
1105 if(fd < 0) {
1106 fd = open(DEBUG_FILE_NAME, O_WRONLY | O_APPEND | O_CREAT);
1107 if(fd >= 0) {
1108 snprintf(debug_message, DEBUG_MESSAGE_LEN,
1109 "cycle_min, bat_millivolts, bat_percent, chgr_state, charge_state, pid_p, pid_i, trickle_sec\n");
1110 write(fd, debug_message, strlen(debug_message));
1111 wrcount = 99; /* force a flush */
1114 if(fd >= 0) {
1115 snprintf(debug_message, DEBUG_MESSAGE_LEN,
1116 "%d, %d, %d, %d, %d, %d, %d, %d\n",
1117 powermgmt_last_cycle_startstop_min, battery_millivolts,
1118 battery_percent, charger_input_state, charge_state,
1119 pid_p, pid_i, trickle_sec);
1120 write(fd, debug_message, strlen(debug_message));
1121 wrcount++;
1124 #endif
1125 handle_auto_poweroff();
1127 #if CONFIG_CHARGING == CHARGING_CONTROL
1128 powermgmt_last_cycle_startstop_min++;
1129 #endif
1133 void powermgmt_init(void)
1135 /* init history to 0 */
1136 memset(power_history, 0x00, sizeof(power_history));
1137 create_thread(power_thread, power_stack, sizeof(power_stack), 0,
1138 power_thread_name IF_PRIO(, PRIORITY_SYSTEM)
1139 IF_COP(, CPU));
1142 #endif /* SIMULATOR */
1144 void sys_poweroff(void)
1146 logf("sys_poweroff()");
1147 /* If the main thread fails to shut down the system, we will force a
1148 power off after an 20 second timeout - 28 seconds if recording */
1149 if (shutdown_timeout == 0)
1151 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1152 pcf50606_reset_timeout(); /* Reset timer on first attempt only */
1153 #endif
1154 #ifdef HAVE_RECORDING
1155 if (audio_status() & AUDIO_STATUS_RECORD)
1156 shutdown_timeout += HZ*8;
1157 #endif
1158 shutdown_timeout += HZ*20;
1161 queue_broadcast(SYS_POWEROFF, 0);
1164 void cancel_shutdown(void)
1166 logf("sys_cancel_shutdown()");
1168 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1169 /* TODO: Move some things to target/ tree */
1170 if (shutdown_timeout)
1171 pcf50606_reset_timeout();
1172 #endif
1174 shutdown_timeout = 0;
1177 /* Various hardware housekeeping tasks relating to shutting down the jukebox */
1178 void shutdown_hw(void)
1180 #ifndef SIMULATOR
1181 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1182 if(fd >= 0) {
1183 close(fd);
1184 fd = -1;
1186 #endif
1187 audio_stop();
1188 if (battery_level_safe()) { /* do not save on critical battery */
1189 #ifdef HAVE_LCD_BITMAP
1190 glyph_cache_save();
1191 #endif
1192 if(ata_disk_is_active())
1193 ata_spindown(1);
1195 while(ata_disk_is_active())
1196 sleep(HZ/10);
1198 #if CONFIG_CODEC != SWCODEC
1199 mp3_shutdown();
1200 #else
1201 audiohw_close();
1202 #endif
1204 /* If HD is still active we try to wait for spindown, otherwise the
1205 shutdown_timeout in power_thread_sleep will force a power off */
1206 while(ata_disk_is_active())
1207 sleep(HZ/10);
1208 #ifndef IAUDIO_X5
1209 lcd_set_contrast(0);
1210 #endif /* IAUDIO_X5 */
1211 #ifdef HAVE_REMOTE_LCD
1212 lcd_remote_set_contrast(0);
1213 #endif
1215 #ifdef HAVE_LCD_SHUTDOWN
1216 lcd_shutdown();
1217 #endif
1219 /* Small delay to make sure all HW gets time to flush. Especially
1220 eeprom chips are quite slow and might be still writing the last
1221 byte. */
1222 sleep(HZ/4);
1223 power_off();
1224 #endif /* #ifndef SIMULATOR */
1227 /* Send system battery level update events on reaching certain significant
1228 levels. This must be called after battery_percent has been updated. */
1229 static void send_battery_level_event(void)
1231 static const int levels[] = { 5, 15, 30, 50, 0 };
1232 const int *level = levels;
1233 while (*level)
1235 if (battery_percent <= *level && last_sent_battery_level > *level)
1237 last_sent_battery_level = *level;
1238 queue_broadcast(SYS_BATTERY_UPDATE, last_sent_battery_level);
1239 break;
1241 level++;