For TCC and IMX Rolo, use a full flush and invalidate before branching.
[kugel-rb.git] / firmware / powermgmt.c
blob69b0704bc2acf0138779780675a23fd23bb49da7
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();
482 else if (battery_millivolts <= battery_level_shutoff[0])
483 powermgmt_est_runningtime_min = 0;
485 else
486 powermgmt_est_runningtime_min = (battery_millivolts -
487 battery_level_shutoff[0]) / 2;
490 battery_percent = level;
491 send_battery_level_event();
495 * We shut off in the following cases:
496 * 1) The unit is idle, not playing music
497 * 2) The unit is playing music, but is paused
498 * 3) The battery level has reached shutdown limit
500 * We do not shut off in the following cases:
501 * 1) The USB is connected
502 * 2) The charger is connected
503 * 3) We are recording, or recording with pause
504 * 4) The radio is playing
506 static void handle_auto_poweroff(void)
508 long timeout = poweroff_timeout*60*HZ;
509 int audio_stat = audio_status();
511 #if CONFIG_CHARGING
513 * Inhibit shutdown as long as the charger is plugged in. If it is
514 * unplugged, wait for a timeout period and then shut down.
516 if(charger_input_state == CHARGER || audio_stat == AUDIO_STATUS_PLAY) {
517 last_event_tick = current_tick;
519 #endif
521 #ifndef NO_LOW_BATTERY_SHUTDOWN
522 /* switch off unit if battery level is too low for reliable operation */
523 if(battery_millivolts < battery_level_shutoff[battery_type]) {
524 if(!shutdown_timeout) {
525 backlight_on();
526 sys_poweroff();
529 #endif
531 if(timeout &&
532 #if CONFIG_TUNER && !defined(BOOTLOADER)
533 (!(get_radio_status() & FMRADIO_PLAYING)) &&
534 #endif
535 !usb_inserted() &&
536 ((audio_stat == 0) ||
537 ((audio_stat == (AUDIO_STATUS_PLAY | AUDIO_STATUS_PAUSE)) &&
538 !sleeptimer_active)))
540 if(TIME_AFTER(current_tick, last_event_tick + timeout) &&
541 TIME_AFTER(current_tick, last_disk_activity + timeout))
543 sys_poweroff();
546 else
548 /* Handle sleeptimer */
549 if(sleeptimer_active && !usb_inserted())
551 if(TIME_AFTER(current_tick, sleeptimer_endtick))
553 audio_stop();
554 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
555 if((charger_input_state == CHARGER) ||
556 (charger_input_state == CHARGER_PLUGGED))
558 DEBUGF("Sleep timer timeout. Stopping...\n");
559 set_sleep_timer(0);
560 backlight_off(); /* Nighty, nighty... */
562 else
563 #endif
565 DEBUGF("Sleep timer timeout. Shutting off...\n");
566 sys_poweroff();
574 * Estimate how much current we are drawing just to run.
576 static int runcurrent(void)
578 int current;
580 #if MEM == 8 && !defined(HAVE_MMC)
581 /* assuming 192 kbps, the running time is 22% longer with 8MB */
582 current = (CURRENT_NORMAL*100/122);
583 #else
584 current = CURRENT_NORMAL;
585 #endif /* MEM == 8 */
587 if(usb_inserted()
588 #if defined(HAVE_USB_POWER)
589 #if (CURRENT_USB < CURRENT_NORMAL)
590 || usb_powered()
591 #else
592 && !usb_powered()
593 #endif
594 #endif
597 current = CURRENT_USB;
600 #if defined(HAVE_BACKLIGHT) && !defined(BOOTLOADER)
601 if (backlight_get_current_timeout() == 0) /* LED always on */
602 current += CURRENT_BACKLIGHT;
603 #endif
605 #if defined(HAVE_RECORDING) && defined(CURRENT_RECORD)
606 if (audio_status() & AUDIO_STATUS_RECORD)
607 current += CURRENT_RECORD;
608 #endif
610 #ifdef HAVE_SPDIF_POWER
611 if (spdif_powered())
612 current += CURRENT_SPDIF_OUT;
613 #endif
615 #ifdef HAVE_REMOTE_LCD
616 if (remote_detect())
617 current += CURRENT_REMOTE;
618 #endif
620 return(current);
624 /* Check to see whether or not we've received an alarm in the last second */
625 #ifdef HAVE_RTC_ALARM
626 static void power_thread_rtc_process(void)
628 if (rtc_check_alarm_flag()) {
629 rtc_enable_alarm(false);
632 #endif
635 * This function is called to do the relativly long sleep waits from within the
636 * main power_thread loop while at the same time servicing any other periodic
637 * functions in the power thread which need to be called at a faster periodic
638 * rate than the slow periodic rate of the main power_thread loop.
640 * While we are waiting for the time to expire, we average the battery
641 * voltages.
643 static void power_thread_sleep(int ticks)
645 int small_ticks;
647 while (ticks > 0) {
649 #if CONFIG_CHARGING
651 * Detect charger plugged/unplugged transitions. On a plugged or
652 * unplugged event, we return immediately, run once through the main
653 * loop (including the subroutines), and end up back here where we
654 * transition to the appropriate steady state charger on/off state.
656 if(charger_inserted()
657 #ifdef HAVE_USB_POWER /* USB powered or USB inserted both provide power */
658 || usb_powered()
659 #if CONFIG_CHARGING
660 || (usb_inserted() && usb_charging_enabled())
661 #endif
662 #endif
664 switch(charger_input_state) {
665 case NO_CHARGER:
666 case CHARGER_UNPLUGGED:
667 charger_input_state = CHARGER_PLUGGED;
668 return;
669 case CHARGER_PLUGGED:
670 queue_broadcast(SYS_CHARGER_CONNECTED, 0);
671 last_sent_battery_level = 0;
672 charger_input_state = CHARGER;
673 break;
674 case CHARGER:
675 break;
677 } else { /* charger not inserted */
678 switch(charger_input_state) {
679 case NO_CHARGER:
680 break;
681 case CHARGER_UNPLUGGED:
682 queue_broadcast(SYS_CHARGER_DISCONNECTED, 0);
683 last_sent_battery_level = 100;
684 charger_input_state = NO_CHARGER;
685 break;
686 case CHARGER_PLUGGED:
687 case CHARGER:
688 charger_input_state = CHARGER_UNPLUGGED;
689 return;
692 #endif
693 #if CONFIG_CHARGING == CHARGING_MONITOR
694 switch (charger_input_state) {
695 case CHARGER_UNPLUGGED:
696 case NO_CHARGER:
697 charge_state = DISCHARGING;
698 break;
699 case CHARGER_PLUGGED:
700 case CHARGER:
701 if (charging_state()) {
702 charge_state = CHARGING;
703 } else {
704 charge_state = DISCHARGING;
706 break;
709 #endif /* CONFIG_CHARGING == CHARGING_MONITOR */
711 small_ticks = MIN(HZ/2, ticks);
712 sleep(small_ticks);
713 ticks -= small_ticks;
715 /* If the power off timeout expires, the main thread has failed
716 to shut down the system, and we need to force a power off */
717 if(shutdown_timeout) {
718 shutdown_timeout -= small_ticks;
719 if(shutdown_timeout <= 0)
720 power_off();
723 #ifdef HAVE_RTC_ALARM
724 power_thread_rtc_process();
725 #endif
728 * Do a digital exponential filter. We don't sample the battery if
729 * the disk is spinning unless we are in USB mode (the disk will most
730 * likely always be spinning in USB mode).
732 if (!ata_disk_is_active() || usb_inserted()) {
733 avgbat += battery_adc_voltage() - (avgbat / BATT_AVE_SAMPLES);
735 * battery_millivolts is the millivolt-scaled filtered battery value.
737 battery_millivolts = avgbat / BATT_AVE_SAMPLES;
739 /* update battery status every time an update is available */
740 battery_status_update();
742 else if (battery_percent < 8) {
743 /* If battery is low, observe voltage during disk activity.
744 * Shut down if voltage drops below shutoff level and we are not
745 * using NiMH or Alkaline batteries.
747 battery_millivolts = (battery_adc_voltage() +
748 battery_millivolts + 1) / 2;
750 /* update battery status every time an update is available */
751 battery_status_update();
753 #ifndef NO_LOW_BATTERY_SHUTDOWN
754 if (!shutdown_timeout &&
755 (battery_millivolts < battery_level_shutoff[battery_type]))
756 sys_poweroff();
757 else
758 #endif
759 avgbat += battery_millivolts - (avgbat / BATT_AVE_SAMPLES);
762 #if CONFIG_CHARGING == CHARGING_CONTROL
763 if (ata_disk_is_active()) {
764 /* flag hdd use for charging calculation */
765 disk_activity_last_cycle = true;
767 #endif
768 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
770 * If we have a lot of pending writes or if the disk is spining,
771 * fsync the debug log file.
773 if((wrcount > 10) || ((wrcount > 0) && ata_disk_is_active())) {
774 fsync(fd);
775 wrcount = 0;
777 #endif
783 * This power thread maintains a history of battery voltage
784 * and implements a charging algorithm.
785 * For a complete description of the charging algorithm read
786 * docs/CHARGING_ALGORITHM.
789 static void power_thread(void)
791 #if CONFIG_CHARGING == CHARGING_CONTROL
792 int i;
793 unsigned int target_voltage = TRICKLE_VOLTAGE; /* desired topoff/trickle
794 * voltage level */
795 int charge_max_time_idle = 0; /* max. charging duration, calculated at
796 * beginning of charging */
797 int charge_max_time_now = 0; /* max. charging duration including
798 * hdd activity */
799 int minutes_disk_activity = 0; /* count minutes of hdd use during
800 * charging */
801 int last_disk_activity = CHARGE_END_LONGD + 1; /* last hdd use x mins ago */
802 #endif
804 /* Delay reading the first battery level */
805 #ifdef MROBE_100
806 while(battery_adc_voltage()>4200) /* gives false readings initially */
807 #endif
808 sleep(HZ/100);
810 /* initialize the voltages for the exponential filter */
811 avgbat = battery_adc_voltage() + 15;
813 #ifndef HAVE_MMC /* this adjustment is only needed for HD based */
814 /* The battery voltage is usually a little lower directly after
815 turning on, because the disk was used heavily. Raise it by 5% */
816 #ifdef HAVE_CHARGING
817 if(!charger_inserted()) /* only if charger not connected */
818 #endif
819 avgbat += (percent_to_volt_discharge[battery_type][6] -
820 percent_to_volt_discharge[battery_type][5]) / 2;
821 #endif /* not HAVE_MMC */
823 avgbat = avgbat * BATT_AVE_SAMPLES;
824 battery_millivolts = avgbat / BATT_AVE_SAMPLES;
826 #if CONFIG_CHARGING
827 if(charger_inserted()) {
828 battery_percent = voltage_to_percent(battery_millivolts,
829 percent_to_volt_charge);
830 #if defined(IRIVER_H100_SERIES) || defined(IRIVER_H300_SERIES)
831 /* Checking for iriver is a temporary kludge. */
832 charger_input_state = CHARGER;
833 #endif
834 } else
835 #endif
836 { battery_percent = voltage_to_percent(battery_millivolts,
837 percent_to_volt_discharge[battery_type]);
838 battery_percent += (battery_percent < 100);
841 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
842 fd = -1;
843 wrcount = 0;
844 #endif
846 while (1)
848 /* rotate the power history */
849 memmove(power_history + 1, power_history,
850 sizeof(power_history) - sizeof(power_history[0]));
852 /* insert new value at the start, in millivolts 8-) */
853 power_history[0] = battery_millivolts;
855 #if CONFIG_CHARGING == CHARGING_CONTROL
856 if (charger_input_state == CHARGER_PLUGGED) {
857 pid_p = 0;
858 pid_i = 0;
859 snprintf(power_message, POWER_MESSAGE_LEN, "Charger plugged in");
861 * The charger was just plugged in. If the battery level is
862 * nearly charged, just trickle. If the battery is low, start
863 * a full charge cycle. If the battery level is in between,
864 * top-off and then trickle.
866 if(battery_percent > START_TOPOFF_CHG) {
867 powermgmt_last_cycle_level = battery_percent;
868 powermgmt_last_cycle_startstop_min = 0;
869 if(battery_percent >= START_TRICKLE_CHG) {
870 charge_state = TRICKLE;
871 target_voltage = TRICKLE_VOLTAGE;
872 } else {
873 charge_state = TOPOFF;
874 target_voltage = TOPOFF_VOLTAGE;
876 } else {
878 * Start the charger full strength
880 i = CHARGE_MAX_TIME_1500 * battery_capacity / 1500;
881 charge_max_time_idle =
882 i * (100 + 35 - battery_percent) / 100;
883 if (charge_max_time_idle > i) {
884 charge_max_time_idle = i;
886 charge_max_time_now = charge_max_time_idle;
888 snprintf(power_message, POWER_MESSAGE_LEN,
889 "ChgAt %d%% max %dm", battery_level(),
890 charge_max_time_now);
892 /* enable the charger after the max time calc is done,
893 because battery_level depends on if the charger is
894 on */
895 DEBUGF("power: charger inserted and battery"
896 " not full, charging\n");
897 powermgmt_last_cycle_level = battery_percent;
898 powermgmt_last_cycle_startstop_min = 0;
899 trickle_sec = 60;
900 long_delta = short_delta = 999999;
901 charge_state = CHARGING;
904 if (charge_state == CHARGING) {
905 /* alter charge time max length with extra disk use */
906 if (disk_activity_last_cycle) {
907 minutes_disk_activity++;
908 charge_max_time_now = charge_max_time_idle +
909 (minutes_disk_activity * 2 / 5);
910 disk_activity_last_cycle = false;
911 last_disk_activity = 0;
912 } else {
913 last_disk_activity++;
916 * Check the delta voltage over the last X minutes so we can do
917 * our end-of-charge logic based on the battery level change.
918 *(no longer use minimum time as logic for charge end has 50
919 * minutes minimum charge built in)
921 if (powermgmt_last_cycle_startstop_min > CHARGE_END_SHORTD) {
922 short_delta = power_history[0] -
923 power_history[CHARGE_END_SHORTD - 1];
926 if (powermgmt_last_cycle_startstop_min > CHARGE_END_LONGD) {
928 * Scan the history: the points where measurement is taken need to
929 * be fairly static. (check prior to short delta 'area')
930 * (also only check first and last 10 cycles - delta in middle OK)
932 long_delta = power_history[0] -
933 power_history[CHARGE_END_LONGD - 1];
935 for(i = CHARGE_END_SHORTD; i < CHARGE_END_SHORTD + 10; i++) {
936 if(((power_history[i] - power_history[i+1]) > 50) ||
937 ((power_history[i] - power_history[i+1]) < -50)) {
938 long_delta = 777777;
939 break;
942 for(i = CHARGE_END_LONGD - 11; i < CHARGE_END_LONGD - 1 ; i++) {
943 if(((power_history[i] - power_history[i+1]) > 50) ||
944 ((power_history[i] - power_history[i+1]) < -50)) {
945 long_delta = 888888;
946 break;
951 snprintf(power_message, POWER_MESSAGE_LEN,
952 "Chg %dm, max %dm", powermgmt_last_cycle_startstop_min,
953 charge_max_time_now);
955 * End of charge criteria (any qualify):
956 * 1) Charged a long time
957 * 2) DeltaV went negative for a short time ( & long delta static)
958 * 3) DeltaV was negative over a longer period (no disk use only)
959 * Note: short_delta and long_delta are millivolts
961 if ((powermgmt_last_cycle_startstop_min >= charge_max_time_now) ||
962 (short_delta <= -50 && long_delta < 50 ) || (long_delta < -20 &&
963 last_disk_activity > CHARGE_END_LONGD)) {
964 if (powermgmt_last_cycle_startstop_min > charge_max_time_now) {
965 DEBUGF("power: powermgmt_last_cycle_startstop_min > charge_max_time_now, "
966 "enough!\n");
968 *have charged too long and deltaV detection did not
969 *work!
971 snprintf(power_message, POWER_MESSAGE_LEN,
972 "Chg tmout %d min", charge_max_time_now);
974 * Switch to trickle charging. We skip the top-off
975 * since we've effectively done the top-off operation
976 * already since we charged for the maximum full
977 * charge time.
979 powermgmt_last_cycle_level = battery_percent;
980 powermgmt_last_cycle_startstop_min = 0;
981 charge_state = TRICKLE;
984 * set trickle charge target to a relative voltage instead
985 * of an arbitrary value - the fully charged voltage may
986 * vary according to ambient temp, battery condition etc
987 * trickle target is -0.15v from full voltage acheived
988 * topup target is -0.05v from full voltage
990 target_voltage = power_history[0] - 150;
992 } else {
993 if(short_delta <= -5) {
994 DEBUGF("power: short-term negative"
995 " delta, enough!\n");
996 snprintf(power_message, POWER_MESSAGE_LEN,
997 "end negd %d %dmin", short_delta,
998 powermgmt_last_cycle_startstop_min);
999 target_voltage = power_history[CHARGE_END_SHORTD - 1]
1000 - 50;
1001 } else {
1002 DEBUGF("power: long-term small "
1003 "positive delta, enough!\n");
1004 snprintf(power_message, POWER_MESSAGE_LEN,
1005 "end lowd %d %dmin", long_delta,
1006 powermgmt_last_cycle_startstop_min);
1007 target_voltage = power_history[CHARGE_END_LONGD - 1]
1008 - 50;
1011 * Switch to top-off charging.
1013 powermgmt_last_cycle_level = battery_percent;
1014 powermgmt_last_cycle_startstop_min = 0;
1015 charge_state = TOPOFF;
1019 else if (charge_state != DISCHARGING) /* top off or trickle */
1022 *Time to switch from topoff to trickle?
1024 if ((charge_state == TOPOFF) &&
1025 (powermgmt_last_cycle_startstop_min > TOPOFF_MAX_TIME))
1027 powermgmt_last_cycle_level = battery_percent;
1028 powermgmt_last_cycle_startstop_min = 0;
1029 charge_state = TRICKLE;
1030 target_voltage = target_voltage - 100;
1033 * Adjust trickle charge time (proportional and integral terms).
1034 * Note: I considered setting the level higher if the USB is
1035 * plugged in, but it doesn't appear to be necessary and will
1036 * generate more heat [gvb].
1039 pid_p = ((signed)target_voltage - (signed)battery_millivolts) / 5;
1040 if((pid_p <= PID_DEADZONE) && (pid_p >= -PID_DEADZONE))
1041 pid_p = 0;
1043 if((unsigned) battery_millivolts < target_voltage) {
1044 if(pid_i < 60) {
1045 pid_i++; /* limit so it doesn't "wind up" */
1047 } else {
1048 if(pid_i > 0) {
1049 pid_i--; /* limit so it doesn't "wind up" */
1053 trickle_sec = pid_p + pid_i;
1055 if(trickle_sec > 60) {
1056 trickle_sec = 60;
1058 if(trickle_sec < 0) {
1059 trickle_sec = 0;
1062 } else if (charge_state == DISCHARGING) {
1063 trickle_sec = 0;
1065 * The charger is enabled here only in one case: if it was
1066 * turned on at boot time (power_init). Turn it off now.
1068 if (charger_enabled)
1069 charger_enable(false);
1072 if (charger_input_state == CHARGER_UNPLUGGED) {
1074 * The charger was just unplugged.
1076 DEBUGF("power: charger disconnected, disabling\n");
1078 charger_enable(false);
1079 powermgmt_last_cycle_level = battery_percent;
1080 powermgmt_last_cycle_startstop_min = 0;
1081 trickle_sec = 0;
1082 pid_p = 0;
1083 pid_i = 0;
1084 charge_state = DISCHARGING;
1085 snprintf(power_message, POWER_MESSAGE_LEN, "Charger: discharge");
1088 #endif /* CONFIG_CHARGING == CHARGING_CONTROL */
1090 /* sleep for a minute */
1092 #if CONFIG_CHARGING == CHARGING_CONTROL
1093 if(trickle_sec > 0) {
1094 charger_enable(true);
1095 power_thread_sleep(HZ * trickle_sec);
1097 if(trickle_sec < 60)
1098 charger_enable(false);
1099 power_thread_sleep(HZ * (60 - trickle_sec));
1100 #else
1101 power_thread_sleep(HZ * 60);
1102 #endif
1104 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1105 if(usb_inserted()) {
1106 if(fd >= 0) {
1107 /* It is probably too late to close the file but we can try...*/
1108 close(fd);
1109 fd = -1;
1111 } else {
1112 if(fd < 0) {
1113 fd = open(DEBUG_FILE_NAME, O_WRONLY | O_APPEND | O_CREAT);
1114 if(fd >= 0) {
1115 snprintf(debug_message, DEBUG_MESSAGE_LEN,
1116 "cycle_min, bat_millivolts, bat_percent, chgr_state, charge_state, pid_p, pid_i, trickle_sec\n");
1117 write(fd, debug_message, strlen(debug_message));
1118 wrcount = 99; /* force a flush */
1121 if(fd >= 0) {
1122 snprintf(debug_message, DEBUG_MESSAGE_LEN,
1123 "%d, %d, %d, %d, %d, %d, %d, %d\n",
1124 powermgmt_last_cycle_startstop_min, battery_millivolts,
1125 battery_percent, charger_input_state, charge_state,
1126 pid_p, pid_i, trickle_sec);
1127 write(fd, debug_message, strlen(debug_message));
1128 wrcount++;
1131 #endif
1132 handle_auto_poweroff();
1134 #if CONFIG_CHARGING == CHARGING_CONTROL
1135 powermgmt_last_cycle_startstop_min++;
1136 #endif
1140 void powermgmt_init(void)
1142 /* init history to 0 */
1143 memset(power_history, 0x00, sizeof(power_history));
1144 create_thread(power_thread, power_stack, sizeof(power_stack), 0,
1145 power_thread_name IF_PRIO(, PRIORITY_SYSTEM)
1146 IF_COP(, CPU));
1149 #endif /* SIMULATOR */
1151 void sys_poweroff(void)
1153 logf("sys_poweroff()");
1154 /* If the main thread fails to shut down the system, we will force a
1155 power off after an 20 second timeout - 28 seconds if recording */
1156 if (shutdown_timeout == 0)
1158 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1159 pcf50606_reset_timeout(); /* Reset timer on first attempt only */
1160 #endif
1161 #ifdef HAVE_RECORDING
1162 if (audio_status() & AUDIO_STATUS_RECORD)
1163 shutdown_timeout += HZ*8;
1164 #endif
1165 shutdown_timeout += HZ*20;
1168 queue_broadcast(SYS_POWEROFF, 0);
1171 void cancel_shutdown(void)
1173 logf("sys_cancel_shutdown()");
1175 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1176 /* TODO: Move some things to target/ tree */
1177 if (shutdown_timeout)
1178 pcf50606_reset_timeout();
1179 #endif
1181 shutdown_timeout = 0;
1184 /* Various hardware housekeeping tasks relating to shutting down the jukebox */
1185 void shutdown_hw(void)
1187 #ifndef SIMULATOR
1188 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1189 if(fd >= 0) {
1190 close(fd);
1191 fd = -1;
1193 #endif
1194 audio_stop();
1195 if (battery_level_safe()) { /* do not save on critical battery */
1196 #ifdef HAVE_LCD_BITMAP
1197 glyph_cache_save();
1198 #endif
1199 if(ata_disk_is_active())
1200 ata_spindown(1);
1202 while(ata_disk_is_active())
1203 sleep(HZ/10);
1205 #if CONFIG_CODEC != SWCODEC
1206 mp3_shutdown();
1207 #else
1208 audiohw_close();
1209 #endif
1211 /* If HD is still active we try to wait for spindown, otherwise the
1212 shutdown_timeout in power_thread_sleep will force a power off */
1213 while(ata_disk_is_active())
1214 sleep(HZ/10);
1215 #ifndef IAUDIO_X5
1216 lcd_set_contrast(0);
1217 #endif /* IAUDIO_X5 */
1218 #ifdef HAVE_REMOTE_LCD
1219 lcd_remote_set_contrast(0);
1220 #endif
1222 #ifdef HAVE_LCD_SHUTDOWN
1223 lcd_shutdown();
1224 #endif
1226 /* Small delay to make sure all HW gets time to flush. Especially
1227 eeprom chips are quite slow and might be still writing the last
1228 byte. */
1229 sleep(HZ/4);
1230 power_off();
1231 #endif /* #ifndef SIMULATOR */
1234 /* Send system battery level update events on reaching certain significant
1235 levels. This must be called after battery_percent has been updated. */
1236 static void send_battery_level_event(void)
1238 static const int levels[] = { 5, 15, 30, 50, 0 };
1239 const int *level = levels;
1240 while (*level)
1242 if (battery_percent <= *level && last_sent_battery_level > *level)
1244 last_sent_battery_level = *level;
1245 queue_broadcast(SYS_BATTERY_UPDATE, last_sent_battery_level);
1246 break;
1248 level++;