Oops. Should commit patches correctly.
[Rockbox.git] / firmware / powermgmt.c
blob072a31fa3fc5e8e29f90c21ac4100c4c9ec6501f
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 #ifdef MROBE_100
802 while(battery_adc_voltage()>4200) /* gives false readings initially */
803 #endif
804 sleep(HZ/100);
806 /* initialize the voltages for the exponential filter */
807 avgbat = battery_adc_voltage() + 15;
809 #ifndef HAVE_MMC /* this adjustment is only needed for HD based */
810 /* The battery voltage is usually a little lower directly after
811 turning on, because the disk was used heavily. Raise it by 5% */
812 #ifdef HAVE_CHARGING
813 if(!charger_inserted()) /* only if charger not connected */
814 #endif
815 avgbat += (percent_to_volt_discharge[battery_type][6] -
816 percent_to_volt_discharge[battery_type][5]) / 2;
817 #endif /* not HAVE_MMC */
819 avgbat = avgbat * BATT_AVE_SAMPLES;
820 battery_millivolts = avgbat / BATT_AVE_SAMPLES;
822 #if CONFIG_CHARGING
823 if(charger_inserted()) {
824 battery_percent = voltage_to_percent(battery_millivolts,
825 percent_to_volt_charge);
826 #if defined(IRIVER_H100_SERIES) || defined(IRIVER_H300_SERIES)
827 /* Checking for iriver is a temporary kludge. */
828 charger_input_state = CHARGER;
829 #endif
830 } else
831 #endif
832 { battery_percent = voltage_to_percent(battery_millivolts,
833 percent_to_volt_discharge[battery_type]);
834 battery_percent += (battery_percent < 100);
837 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
838 fd = -1;
839 wrcount = 0;
840 #endif
842 while (1)
844 /* rotate the power history */
845 memmove(power_history + 1, power_history,
846 sizeof(power_history) - sizeof(power_history[0]));
848 /* insert new value at the start, in millivolts 8-) */
849 power_history[0] = battery_millivolts;
851 #if CONFIG_CHARGING == CHARGING_CONTROL
852 if (charger_input_state == CHARGER_PLUGGED) {
853 pid_p = 0;
854 pid_i = 0;
855 snprintf(power_message, POWER_MESSAGE_LEN, "Charger plugged in");
857 * The charger was just plugged in. If the battery level is
858 * nearly charged, just trickle. If the battery is low, start
859 * a full charge cycle. If the battery level is in between,
860 * top-off and then trickle.
862 if(battery_percent > START_TOPOFF_CHG) {
863 powermgmt_last_cycle_level = battery_percent;
864 powermgmt_last_cycle_startstop_min = 0;
865 if(battery_percent >= START_TRICKLE_CHG) {
866 charge_state = TRICKLE;
867 target_voltage = TRICKLE_VOLTAGE;
868 } else {
869 charge_state = TOPOFF;
870 target_voltage = TOPOFF_VOLTAGE;
872 } else {
874 * Start the charger full strength
876 i = CHARGE_MAX_TIME_1500 * battery_capacity / 1500;
877 charge_max_time_idle =
878 i * (100 + 35 - battery_percent) / 100;
879 if (charge_max_time_idle > i) {
880 charge_max_time_idle = i;
882 charge_max_time_now = charge_max_time_idle;
884 snprintf(power_message, POWER_MESSAGE_LEN,
885 "ChgAt %d%% max %dm", battery_level(),
886 charge_max_time_now);
888 /* enable the charger after the max time calc is done,
889 because battery_level depends on if the charger is
890 on */
891 DEBUGF("power: charger inserted and battery"
892 " not full, charging\n");
893 powermgmt_last_cycle_level = battery_percent;
894 powermgmt_last_cycle_startstop_min = 0;
895 trickle_sec = 60;
896 long_delta = short_delta = 999999;
897 charge_state = CHARGING;
900 if (charge_state == CHARGING) {
901 /* alter charge time max length with extra disk use */
902 if (disk_activity_last_cycle) {
903 minutes_disk_activity++;
904 charge_max_time_now = charge_max_time_idle +
905 (minutes_disk_activity * 2 / 5);
906 disk_activity_last_cycle = false;
907 last_disk_activity = 0;
908 } else {
909 last_disk_activity++;
912 * Check the delta voltage over the last X minutes so we can do
913 * our end-of-charge logic based on the battery level change.
914 *(no longer use minimum time as logic for charge end has 50
915 * minutes minimum charge built in)
917 if (powermgmt_last_cycle_startstop_min > CHARGE_END_SHORTD) {
918 short_delta = power_history[0] -
919 power_history[CHARGE_END_SHORTD - 1];
922 if (powermgmt_last_cycle_startstop_min > CHARGE_END_LONGD) {
924 * Scan the history: the points where measurement is taken need to
925 * be fairly static. (check prior to short delta 'area')
926 * (also only check first and last 10 cycles - delta in middle OK)
928 long_delta = power_history[0] -
929 power_history[CHARGE_END_LONGD - 1];
931 for(i = CHARGE_END_SHORTD; i < CHARGE_END_SHORTD + 10; i++) {
932 if(((power_history[i] - power_history[i+1]) > 50) ||
933 ((power_history[i] - power_history[i+1]) < -50)) {
934 long_delta = 777777;
935 break;
938 for(i = CHARGE_END_LONGD - 11; i < CHARGE_END_LONGD - 1 ; i++) {
939 if(((power_history[i] - power_history[i+1]) > 50) ||
940 ((power_history[i] - power_history[i+1]) < -50)) {
941 long_delta = 888888;
942 break;
947 snprintf(power_message, POWER_MESSAGE_LEN,
948 "Chg %dm, max %dm", powermgmt_last_cycle_startstop_min,
949 charge_max_time_now);
951 * End of charge criteria (any qualify):
952 * 1) Charged a long time
953 * 2) DeltaV went negative for a short time ( & long delta static)
954 * 3) DeltaV was negative over a longer period (no disk use only)
955 * Note: short_delta and long_delta are millivolts
957 if ((powermgmt_last_cycle_startstop_min >= charge_max_time_now) ||
958 (short_delta <= -50 && long_delta < 50 ) || (long_delta < -20 &&
959 last_disk_activity > CHARGE_END_LONGD)) {
960 if (powermgmt_last_cycle_startstop_min > charge_max_time_now) {
961 DEBUGF("power: powermgmt_last_cycle_startstop_min > charge_max_time_now, "
962 "enough!\n");
964 *have charged too long and deltaV detection did not
965 *work!
967 snprintf(power_message, POWER_MESSAGE_LEN,
968 "Chg tmout %d min", charge_max_time_now);
970 * Switch to trickle charging. We skip the top-off
971 * since we've effectively done the top-off operation
972 * already since we charged for the maximum full
973 * charge time.
975 powermgmt_last_cycle_level = battery_percent;
976 powermgmt_last_cycle_startstop_min = 0;
977 charge_state = TRICKLE;
980 * set trickle charge target to a relative voltage instead
981 * of an arbitrary value - the fully charged voltage may
982 * vary according to ambient temp, battery condition etc
983 * trickle target is -0.15v from full voltage acheived
984 * topup target is -0.05v from full voltage
986 target_voltage = power_history[0] - 150;
988 } else {
989 if(short_delta <= -5) {
990 DEBUGF("power: short-term negative"
991 " delta, enough!\n");
992 snprintf(power_message, POWER_MESSAGE_LEN,
993 "end negd %d %dmin", short_delta,
994 powermgmt_last_cycle_startstop_min);
995 target_voltage = power_history[CHARGE_END_SHORTD - 1]
996 - 50;
997 } else {
998 DEBUGF("power: long-term small "
999 "positive delta, enough!\n");
1000 snprintf(power_message, POWER_MESSAGE_LEN,
1001 "end lowd %d %dmin", long_delta,
1002 powermgmt_last_cycle_startstop_min);
1003 target_voltage = power_history[CHARGE_END_LONGD - 1]
1004 - 50;
1007 * Switch to top-off charging.
1009 powermgmt_last_cycle_level = battery_percent;
1010 powermgmt_last_cycle_startstop_min = 0;
1011 charge_state = TOPOFF;
1015 else if (charge_state != DISCHARGING) /* top off or trickle */
1018 *Time to switch from topoff to trickle?
1020 if ((charge_state == TOPOFF) &&
1021 (powermgmt_last_cycle_startstop_min > TOPOFF_MAX_TIME))
1023 powermgmt_last_cycle_level = battery_percent;
1024 powermgmt_last_cycle_startstop_min = 0;
1025 charge_state = TRICKLE;
1026 target_voltage = target_voltage - 100;
1029 * Adjust trickle charge time (proportional and integral terms).
1030 * Note: I considered setting the level higher if the USB is
1031 * plugged in, but it doesn't appear to be necessary and will
1032 * generate more heat [gvb].
1035 pid_p = ((signed)target_voltage - (signed)battery_millivolts) / 5;
1036 if((pid_p <= PID_DEADZONE) && (pid_p >= -PID_DEADZONE))
1037 pid_p = 0;
1039 if((unsigned) battery_millivolts < target_voltage) {
1040 if(pid_i < 60) {
1041 pid_i++; /* limit so it doesn't "wind up" */
1043 } else {
1044 if(pid_i > 0) {
1045 pid_i--; /* limit so it doesn't "wind up" */
1049 trickle_sec = pid_p + pid_i;
1051 if(trickle_sec > 60) {
1052 trickle_sec = 60;
1054 if(trickle_sec < 0) {
1055 trickle_sec = 0;
1058 } else if (charge_state == DISCHARGING) {
1059 trickle_sec = 0;
1061 * The charger is enabled here only in one case: if it was
1062 * turned on at boot time (power_init). Turn it off now.
1064 if (charger_enabled)
1065 charger_enable(false);
1068 if (charger_input_state == CHARGER_UNPLUGGED) {
1070 * The charger was just unplugged.
1072 DEBUGF("power: charger disconnected, disabling\n");
1074 charger_enable(false);
1075 powermgmt_last_cycle_level = battery_percent;
1076 powermgmt_last_cycle_startstop_min = 0;
1077 trickle_sec = 0;
1078 pid_p = 0;
1079 pid_i = 0;
1080 charge_state = DISCHARGING;
1081 snprintf(power_message, POWER_MESSAGE_LEN, "Charger: discharge");
1084 #endif /* CONFIG_CHARGING == CHARGING_CONTROL */
1086 /* sleep for a minute */
1088 #if CONFIG_CHARGING == CHARGING_CONTROL
1089 if(trickle_sec > 0) {
1090 charger_enable(true);
1091 power_thread_sleep(HZ * trickle_sec);
1093 if(trickle_sec < 60)
1094 charger_enable(false);
1095 power_thread_sleep(HZ * (60 - trickle_sec));
1096 #else
1097 power_thread_sleep(HZ * 60);
1098 #endif
1100 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1101 if(usb_inserted()) {
1102 if(fd >= 0) {
1103 /* It is probably too late to close the file but we can try...*/
1104 close(fd);
1105 fd = -1;
1107 } else {
1108 if(fd < 0) {
1109 fd = open(DEBUG_FILE_NAME, O_WRONLY | O_APPEND | O_CREAT);
1110 if(fd >= 0) {
1111 snprintf(debug_message, DEBUG_MESSAGE_LEN,
1112 "cycle_min, bat_millivolts, bat_percent, chgr_state, charge_state, pid_p, pid_i, trickle_sec\n");
1113 write(fd, debug_message, strlen(debug_message));
1114 wrcount = 99; /* force a flush */
1117 if(fd >= 0) {
1118 snprintf(debug_message, DEBUG_MESSAGE_LEN,
1119 "%d, %d, %d, %d, %d, %d, %d, %d\n",
1120 powermgmt_last_cycle_startstop_min, battery_millivolts,
1121 battery_percent, charger_input_state, charge_state,
1122 pid_p, pid_i, trickle_sec);
1123 write(fd, debug_message, strlen(debug_message));
1124 wrcount++;
1127 #endif
1128 handle_auto_poweroff();
1130 #if CONFIG_CHARGING == CHARGING_CONTROL
1131 powermgmt_last_cycle_startstop_min++;
1132 #endif
1136 void powermgmt_init(void)
1138 /* init history to 0 */
1139 memset(power_history, 0x00, sizeof(power_history));
1140 create_thread(power_thread, power_stack, sizeof(power_stack), 0,
1141 power_thread_name IF_PRIO(, PRIORITY_SYSTEM)
1142 IF_COP(, CPU));
1145 #endif /* SIMULATOR */
1147 void sys_poweroff(void)
1149 logf("sys_poweroff()");
1150 /* If the main thread fails to shut down the system, we will force a
1151 power off after an 20 second timeout - 28 seconds if recording */
1152 if (shutdown_timeout == 0)
1154 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1155 pcf50606_reset_timeout(); /* Reset timer on first attempt only */
1156 #endif
1157 #ifdef HAVE_RECORDING
1158 if (audio_status() & AUDIO_STATUS_RECORD)
1159 shutdown_timeout += HZ*8;
1160 #endif
1161 shutdown_timeout += HZ*20;
1164 queue_broadcast(SYS_POWEROFF, 0);
1167 void cancel_shutdown(void)
1169 logf("sys_cancel_shutdown()");
1171 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1172 /* TODO: Move some things to target/ tree */
1173 if (shutdown_timeout)
1174 pcf50606_reset_timeout();
1175 #endif
1177 shutdown_timeout = 0;
1180 /* Various hardware housekeeping tasks relating to shutting down the jukebox */
1181 void shutdown_hw(void)
1183 #ifndef SIMULATOR
1184 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1185 if(fd >= 0) {
1186 close(fd);
1187 fd = -1;
1189 #endif
1190 audio_stop();
1191 if (battery_level_safe()) { /* do not save on critical battery */
1192 #ifdef HAVE_LCD_BITMAP
1193 glyph_cache_save();
1194 #endif
1195 if(ata_disk_is_active())
1196 ata_spindown(1);
1198 while(ata_disk_is_active())
1199 sleep(HZ/10);
1201 #if CONFIG_CODEC != SWCODEC
1202 mp3_shutdown();
1203 #else
1204 audiohw_close();
1205 #endif
1207 /* If HD is still active we try to wait for spindown, otherwise the
1208 shutdown_timeout in power_thread_sleep will force a power off */
1209 while(ata_disk_is_active())
1210 sleep(HZ/10);
1211 #ifndef IAUDIO_X5
1212 lcd_set_contrast(0);
1213 #endif /* IAUDIO_X5 */
1214 #ifdef HAVE_REMOTE_LCD
1215 lcd_remote_set_contrast(0);
1216 #endif
1218 #ifdef HAVE_LCD_SHUTDOWN
1219 lcd_shutdown();
1220 #endif
1222 /* Small delay to make sure all HW gets time to flush. Especially
1223 eeprom chips are quite slow and might be still writing the last
1224 byte. */
1225 sleep(HZ/4);
1226 power_off();
1227 #endif /* #ifndef SIMULATOR */
1230 /* Send system battery level update events on reaching certain significant
1231 levels. This must be called after battery_percent has been updated. */
1232 static void send_battery_level_event(void)
1234 static const int levels[] = { 5, 15, 30, 50, 0 };
1235 const int *level = levels;
1236 while (*level)
1238 if (battery_percent <= *level && last_sent_battery_level > *level)
1240 last_sent_battery_level = *level;
1241 queue_broadcast(SYS_BATTERY_UPDATE, last_sent_battery_level);
1242 break;
1244 level++;