Fix FS#8196 - Gather Runtime Data > User Rating not working
[Rockbox.git] / firmware / powermgmt.c
blob54e759298711ab9d68bb0fedf36e1d2aa27685b1
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 static const unsigned char poweroff_idle_timeout_value[15] =
202 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 30, 45, 60
205 #if CONFIG_CHARGING == CHARGING_CONTROL
206 int long_delta; /* long term delta battery voltage */
207 int short_delta; /* short term delta battery voltage */
208 bool disk_activity_last_cycle = false; /* flag set to aid charger time
209 * calculation */
210 char power_message[POWER_MESSAGE_LEN] = ""; /* message that's shown in
211 debug menu */
212 /* percentage at which charging
213 starts */
214 int powermgmt_last_cycle_startstop_min = 0; /* how many minutes ago was the
215 charging started or
216 stopped? */
217 int powermgmt_last_cycle_level = 0; /* which level had the
218 batteries at this time? */
219 int trickle_sec = 0; /* how many seconds should the
220 charger be enabled per
221 minute for trickle
222 charging? */
223 int pid_p = 0; /* PID proportional term */
224 int pid_i = 0; /* PID integral term */
225 #endif /* CONFIG_CHARGING == CHARGING_CONTROL */
228 * Average battery voltage and charger voltage, filtered via a digital
229 * exponential filter.
231 static unsigned int avgbat; /* average battery voltage (filtering) */
232 static unsigned int battery_millivolts;/* filtered battery voltage, millivolts */
234 #ifdef HAVE_CHARGE_CTRL
235 #define BATT_AVE_SAMPLES 32 /* filter constant / @ 2Hz sample rate */
236 #else
237 #define BATT_AVE_SAMPLES 128 /* slw filter constant for all others */
238 #endif
240 /* battery level (0-100%) of this minute, updated once per minute */
241 static int battery_percent = -1;
242 static int battery_capacity = BATTERY_CAPACITY_DEFAULT; /* default value, mAh */
243 #if BATTERY_TYPES_COUNT > 1
244 static int battery_type = 0;
245 #else
246 #define battery_type 0
247 #endif
249 /* Power history: power_history[0] is the newest sample */
250 unsigned short power_history[POWER_HISTORY_LEN];
252 static char power_stack[DEFAULT_STACK_SIZE/2 + DEBUG_STACK];
253 static const char power_thread_name[] = "power";
255 static int poweroff_timeout = 0;
256 static int powermgmt_est_runningtime_min = -1;
258 static bool sleeptimer_active = false;
259 static long sleeptimer_endtick;
261 static long last_event_tick;
263 static int voltage_to_battery_level(int battery_millivolts);
264 static void battery_status_update(void);
265 static int runcurrent(void);
267 void battery_read_info(int *voltage, int *level)
269 int millivolts = battery_adc_voltage();
271 if (voltage)
272 *voltage = millivolts;
274 if (level)
275 *level = voltage_to_battery_level(millivolts);
278 void reset_poweroff_timer(void)
280 last_event_tick = current_tick;
283 #if BATTERY_TYPES_COUNT > 1
284 void set_battery_type(int type)
286 if (type != battery_type) {
287 battery_type = type;
288 battery_status_update(); /* recalculate the battery status */
291 #endif
293 void set_battery_capacity(int capacity)
295 battery_capacity = capacity;
296 if (battery_capacity > BATTERY_CAPACITY_MAX)
297 battery_capacity = BATTERY_CAPACITY_MAX;
298 if (battery_capacity < BATTERY_CAPACITY_MIN)
299 battery_capacity = BATTERY_CAPACITY_MIN;
300 battery_status_update(); /* recalculate the battery status */
303 int battery_time(void)
305 return powermgmt_est_runningtime_min;
308 /* Returns battery level in percent */
309 int battery_level(void)
311 return battery_percent;
314 /* Returns filtered battery voltage [millivolts] */
315 unsigned int battery_voltage(void)
317 return battery_millivolts;
320 /* Tells if the battery level is safe for disk writes */
321 bool battery_level_safe(void)
323 return battery_millivolts > battery_level_dangerous[battery_type];
326 void set_poweroff_timeout(int timeout)
328 poweroff_timeout = timeout;
331 void set_sleep_timer(int seconds)
333 if(seconds) {
334 sleeptimer_active = true;
335 sleeptimer_endtick = current_tick + seconds * HZ;
337 else {
338 sleeptimer_active = false;
339 sleeptimer_endtick = 0;
343 int get_sleep_timer(void)
345 if(sleeptimer_active)
346 return (sleeptimer_endtick - current_tick) / HZ;
347 else
348 return 0;
351 /* look into the percent_to_volt_* table and get a realistic battery level */
352 static int voltage_to_percent(int voltage, const short* table)
354 if (voltage <= table[0])
355 return 0;
356 else
357 if (voltage >= table[10])
358 return 100;
359 else {
360 /* search nearest value */
361 int i = 0;
362 while ((i < 10) && (table[i+1] < voltage))
363 i++;
364 /* interpolate linear between the smaller and greater value */
365 return (i * 10) /* Tens digit, 10% per entry */
366 + (((voltage - table[i]) * 10)
367 / (table[i+1] - table[i])); /* Ones digit: interpolated */
371 /* update battery level and estimated runtime, called once per minute or
372 * when battery capacity / type settings are changed */
373 static int voltage_to_battery_level(int battery_millivolts)
375 int level;
377 #if defined(CONFIG_CHARGER) \
378 && (defined(IRIVER_H100_SERIES) || defined(IRIVER_H300_SERIES))
379 /* Checking for iriver is a temporary kludge.
380 * This code needs rework/unification */
381 if (charger_input_state == NO_CHARGER) {
382 /* discharging. calculate new battery level and average with last */
383 level = voltage_to_percent(battery_millivolts,
384 percent_to_volt_discharge[battery_type]);
385 if (level != (battery_percent - 1))
386 level = (level + battery_percent + 1) / 2;
388 else if (charger_input_state == CHARGER_UNPLUGGED) {
389 /* just unplugged. adjust filtered values */
390 battery_millivolts -= percent_to_volt_charge[battery_percent/10] -
391 percent_to_volt_discharge[0][battery_percent/10];
392 avgbat = battery_millivolts * 1000 * BATT_AVE_SAMPLES;
393 level = battery_percent;
395 else if (charger_input_state == CHARGER_PLUGGED) {
396 /* just plugged in. adjust battery values */
397 battery_millivolts += percent_to_volt_charge[battery_percent/10] -
398 percent_to_volt_discharge[0][battery_percent/10];
399 avgbat = battery_millivolts * 1000 * BATT_AVE_SAMPLES;
400 level = MIN(12 * battery_percent / 10, 99);
402 else { /* charging. calculate new battery level */
403 level = voltage_to_percent(battery_millivolts,
404 percent_to_volt_charge);
406 #elif CONFIG_CHARGING >= CHARGING_MONITOR
407 if (charge_state == DISCHARGING) {
408 level = voltage_to_percent(battery_millivolts,
409 percent_to_volt_discharge[battery_type]);
411 else if (charge_state == CHARGING) {
412 /* battery level is defined to be < 100% until charging is finished */
413 level = MIN(voltage_to_percent(battery_millivolts,
414 percent_to_volt_charge), 99);
416 else { /* in topoff/trickle charge, battery is by definition 100% full */
417 level = 100;
419 #else
420 /* always use the discharge table */
421 level = voltage_to_percent(battery_millivolts,
422 percent_to_volt_discharge[battery_type]);
423 #endif
425 return level;
428 static void battery_status_update(void)
430 int level = voltage_to_battery_level(battery_millivolts);
432 /* calculate estimated remaining running time */
433 /* discharging: remaining running time */
434 /* charging: remaining charging time */
435 #if CONFIG_CHARGING >= CHARGING_MONITOR
436 if (charge_state == CHARGING) {
437 powermgmt_est_runningtime_min = (100 - level) * battery_capacity * 60
438 / 100 / (CURRENT_MAX_CHG - runcurrent());
440 else
441 #elif CONFIG_CHARGING \
442 && (defined(IRIVER_H100_SERIES) || defined(IRIVER_H300_SERIES))
443 /* Checking for iriver is a temporary kludge.
444 * This code needs rework/unification */
445 if (charger_inserted()) {
446 #ifdef IRIVER_H300_SERIES
447 /* H300_SERIES use CURRENT_MAX_CHG for basic charge time (80%)
448 * plus 110 min top off charge time */
449 powermgmt_est_runningtime_min = ((100-level) * battery_capacity * 80
450 /100 / CURRENT_MAX_CHG) + 110;
451 #else
452 /* H100_SERIES scaled for 160 min basic charge time (80%) on
453 * 1600 mAh battery plus 110 min top off charge time */
454 powermgmt_est_runningtime_min = ((100 - level) * battery_capacity
455 / 993) + 110;
456 #endif
457 level = (level * 80) / 100;
458 if (level > 72) { /* > 91% */
459 int i = POWER_HISTORY_LEN;
460 int d = 1;
461 #ifdef HAVE_CHARGE_STATE
462 if (charge_state == DISCHARGING)
463 d = -2;
464 #endif
465 while ((i > 2) && (d > 0)) /* search zero or neg. delta */
466 d = power_history[0] - power_history[--i];
467 if ((((d == 0) && (i > 6)) || (d == -1)) && (i < 118)) {
468 /* top off charging */
469 level = MIN(80 + (i*19 / 113), 99); /* show 81% .. 99% */
470 powermgmt_est_runningtime_min = MAX(116 - i, 0);
472 else if ((d < 0) || (i > 117)) {
473 /* charging finished */
474 level = 100;
475 powermgmt_est_runningtime_min = battery_capacity * 60
476 / runcurrent();
480 else
481 #endif /* BATT_LIPOL1300 */
483 if ((battery_millivolts + 20) > percent_to_volt_discharge[0][0])
484 powermgmt_est_runningtime_min = (level + battery_percent) * 60 *
485 battery_capacity / 200 / runcurrent();
486 else
487 powermgmt_est_runningtime_min = (battery_millivolts -
488 battery_level_shutoff[0]) / 2;
491 battery_percent = level;
492 send_battery_level_event();
496 * We shut off in the following cases:
497 * 1) The unit is idle, not playing music
498 * 2) The unit is playing music, but is paused
499 * 3) The battery level has reached shutdown limit
501 * We do not shut off in the following cases:
502 * 1) The USB is connected
503 * 2) The charger is connected
504 * 3) We are recording, or recording with pause
505 * 4) The radio is playing
507 static void handle_auto_poweroff(void)
509 long timeout = poweroff_idle_timeout_value[poweroff_timeout]*60*HZ;
510 int audio_stat = audio_status();
512 #if CONFIG_CHARGING
514 * Inhibit shutdown as long as the charger is plugged in. If it is
515 * unplugged, wait for a timeout period and then shut down.
517 if(charger_input_state == CHARGER || audio_stat == AUDIO_STATUS_PLAY) {
518 last_event_tick = current_tick;
520 #endif
522 #ifndef NO_LOW_BATTERY_SHUTDOWN
523 /* switch off unit if battery level is too low for reliable operation */
524 if(battery_millivolts < battery_level_shutoff[battery_type]) {
525 if(!shutdown_timeout) {
526 backlight_on();
527 sys_poweroff();
530 #endif
532 if(timeout &&
533 #if CONFIG_TUNER && !defined(BOOTLOADER)
534 (!(get_radio_status() & FMRADIO_PLAYING)) &&
535 #endif
536 !usb_inserted() &&
537 ((audio_stat == 0) ||
538 ((audio_stat == (AUDIO_STATUS_PLAY | AUDIO_STATUS_PAUSE)) &&
539 !sleeptimer_active)))
541 if(TIME_AFTER(current_tick, last_event_tick + timeout) &&
542 TIME_AFTER(current_tick, last_disk_activity + timeout))
544 sys_poweroff();
547 else
549 /* Handle sleeptimer */
550 if(sleeptimer_active && !usb_inserted())
552 if(TIME_AFTER(current_tick, sleeptimer_endtick))
554 audio_stop();
555 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
556 if((charger_input_state == CHARGER) ||
557 (charger_input_state == CHARGER_PLUGGED))
559 DEBUGF("Sleep timer timeout. Stopping...\n");
560 set_sleep_timer(0);
561 backlight_off(); /* Nighty, nighty... */
563 else
564 #endif
566 DEBUGF("Sleep timer timeout. Shutting off...\n");
567 sys_poweroff();
575 * Estimate how much current we are drawing just to run.
577 static int runcurrent(void)
579 int current;
581 #if MEM == 8 && !defined(HAVE_MMC)
582 /* assuming 192 kbps, the running time is 22% longer with 8MB */
583 current = (CURRENT_NORMAL*100/122);
584 #else
585 current = CURRENT_NORMAL;
586 #endif /* MEM == 8 */
588 if(usb_inserted()
589 #if defined(HAVE_USB_POWER)
590 #if (CURRENT_USB < CURRENT_NORMAL)
591 || usb_powered()
592 #else
593 && !usb_powered()
594 #endif
595 #endif
598 current = CURRENT_USB;
601 #if defined(HAVE_BACKLIGHT) && !defined(BOOTLOADER)
602 if (backlight_get_current_timeout() == 0) /* LED always on */
603 current += CURRENT_BACKLIGHT;
604 #endif
606 #if defined(HAVE_RECORDING) && defined(CURRENT_RECORD)
607 if (audio_status() & AUDIO_STATUS_RECORD)
608 current += CURRENT_RECORD;
609 #endif
611 #ifdef HAVE_SPDIF_POWER
612 if (spdif_powered())
613 current += CURRENT_SPDIF_OUT;
614 #endif
616 #ifdef HAVE_REMOTE_LCD
617 if (remote_detect())
618 current += CURRENT_REMOTE;
619 #endif
621 return(current);
625 /* Check to see whether or not we've received an alarm in the last second */
626 #ifdef HAVE_RTC_ALARM
627 static void power_thread_rtc_process(void)
629 if (rtc_check_alarm_flag()) {
630 rtc_enable_alarm(false);
633 #endif
636 * This function is called to do the relativly long sleep waits from within the
637 * main power_thread loop while at the same time servicing any other periodic
638 * functions in the power thread which need to be called at a faster periodic
639 * rate than the slow periodic rate of the main power_thread loop.
641 * While we are waiting for the time to expire, we average the battery
642 * voltages.
644 static void power_thread_sleep(int ticks)
646 int small_ticks;
648 while (ticks > 0) {
650 #if CONFIG_CHARGING
652 * Detect charger plugged/unplugged transitions. On a plugged or
653 * unplugged event, we return immediately, run once through the main
654 * loop (including the subroutines), and end up back here where we
655 * transition to the appropriate steady state charger on/off state.
657 if(charger_inserted()
658 #ifdef HAVE_USB_POWER /* USB powered or USB inserted both provide power */
659 || usb_powered()
660 #if CONFIG_CHARGING
661 || (usb_inserted() && usb_charging_enabled())
662 #endif
663 #endif
665 switch(charger_input_state) {
666 case NO_CHARGER:
667 case CHARGER_UNPLUGGED:
668 charger_input_state = CHARGER_PLUGGED;
669 return;
670 case CHARGER_PLUGGED:
671 queue_broadcast(SYS_CHARGER_CONNECTED, 0);
672 last_sent_battery_level = 0;
673 charger_input_state = CHARGER;
674 break;
675 case CHARGER:
676 break;
678 } else { /* charger not inserted */
679 switch(charger_input_state) {
680 case NO_CHARGER:
681 break;
682 case CHARGER_UNPLUGGED:
683 queue_broadcast(SYS_CHARGER_DISCONNECTED, 0);
684 last_sent_battery_level = 100;
685 charger_input_state = NO_CHARGER;
686 break;
687 case CHARGER_PLUGGED:
688 case CHARGER:
689 charger_input_state = CHARGER_UNPLUGGED;
690 return;
693 #endif
694 #if CONFIG_CHARGING == CHARGING_MONITOR
695 switch (charger_input_state) {
696 case CHARGER_UNPLUGGED:
697 case NO_CHARGER:
698 charge_state = DISCHARGING;
699 break;
700 case CHARGER_PLUGGED:
701 case CHARGER:
702 if (charging_state()) {
703 charge_state = CHARGING;
704 } else {
705 charge_state = DISCHARGING;
707 break;
710 #endif /* CONFIG_CHARGING == CHARGING_MONITOR */
712 small_ticks = MIN(HZ/2, ticks);
713 sleep(small_ticks);
714 ticks -= small_ticks;
716 /* If the power off timeout expires, the main thread has failed
717 to shut down the system, and we need to force a power off */
718 if(shutdown_timeout) {
719 shutdown_timeout -= small_ticks;
720 if(shutdown_timeout <= 0)
721 power_off();
724 #ifdef HAVE_RTC_ALARM
725 power_thread_rtc_process();
726 #endif
729 * Do a digital exponential filter. We don't sample the battery if
730 * the disk is spinning unless we are in USB mode (the disk will most
731 * likely always be spinning in USB mode).
733 if (!ata_disk_is_active() || usb_inserted()) {
734 avgbat += battery_adc_voltage() - (avgbat / BATT_AVE_SAMPLES);
736 * battery_millivolts is the millivolt-scaled filtered battery value.
738 battery_millivolts = avgbat / BATT_AVE_SAMPLES;
740 /* update battery status every time an update is available */
741 battery_status_update();
743 else if (battery_percent < 8) {
744 /* If battery is low, observe voltage during disk activity.
745 * Shut down if voltage drops below shutoff level and we are not
746 * using NiMH or Alkaline batteries.
748 battery_millivolts = (battery_adc_voltage() +
749 battery_millivolts + 1) / 2;
751 /* update battery status every time an update is available */
752 battery_status_update();
754 #ifndef NO_LOW_BATTERY_SHUTDOWN
755 if (!shutdown_timeout &&
756 (battery_millivolts < battery_level_shutoff[battery_type]))
757 sys_poweroff();
758 else
759 #endif
760 avgbat += battery_millivolts - (avgbat / BATT_AVE_SAMPLES);
763 #if CONFIG_CHARGING == CHARGING_CONTROL
764 if (ata_disk_is_active()) {
765 /* flag hdd use for charging calculation */
766 disk_activity_last_cycle = true;
768 #endif
769 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
771 * If we have a lot of pending writes or if the disk is spining,
772 * fsync the debug log file.
774 if((wrcount > 10) || ((wrcount > 0) && ata_disk_is_active())) {
775 fsync(fd);
776 wrcount = 0;
778 #endif
784 * This power thread maintains a history of battery voltage
785 * and implements a charging algorithm.
786 * For a complete description of the charging algorithm read
787 * docs/CHARGING_ALGORITHM.
790 static void power_thread(void)
792 #if CONFIG_CHARGING == CHARGING_CONTROL
793 int i;
794 unsigned int target_voltage = TRICKLE_VOLTAGE; /* desired topoff/trickle
795 * voltage level */
796 int charge_max_time_idle = 0; /* max. charging duration, calculated at
797 * beginning of charging */
798 int charge_max_time_now = 0; /* max. charging duration including
799 * hdd activity */
800 int minutes_disk_activity = 0; /* count minutes of hdd use during
801 * charging */
802 int last_disk_activity = CHARGE_END_LONGD + 1; /* last hdd use x mins ago */
803 #endif
805 /* initialize the voltages for the exponential filter */
806 avgbat = battery_adc_voltage() + 15;
808 #ifndef HAVE_MMC /* this adjustment is only needed for HD based */
809 /* The battery voltage is usually a little lower directly after
810 turning on, because the disk was used heavily. Raise it by 5% */
811 #ifdef HAVE_CHARGING
812 if(!charger_inserted()) /* only if charger not connected */
813 #endif
814 avgbat += (percent_to_volt_discharge[battery_type][6] -
815 percent_to_volt_discharge[battery_type][5]) / 2;
816 #endif /* not HAVE_MMC */
818 avgbat = avgbat * BATT_AVE_SAMPLES;
819 battery_millivolts = avgbat / BATT_AVE_SAMPLES;
821 #if CONFIG_CHARGING
822 if(charger_inserted()) {
823 battery_percent = voltage_to_percent(battery_millivolts,
824 percent_to_volt_charge);
825 #if defined(IRIVER_H100_SERIES) || defined(IRIVER_H300_SERIES)
826 /* Checking for iriver is a temporary kludge. */
827 charger_input_state = CHARGER;
828 #endif
829 } else
830 #endif
831 { battery_percent = voltage_to_percent(battery_millivolts,
832 percent_to_volt_discharge[battery_type]);
833 battery_percent += (battery_percent < 100);
836 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
837 fd = -1;
838 wrcount = 0;
839 #endif
841 while (1)
843 /* rotate the power history */
844 memmove(power_history + 1, power_history,
845 sizeof(power_history) - sizeof(power_history[0]));
847 /* insert new value at the start, in millivolts 8-) */
848 power_history[0] = battery_millivolts;
850 #if CONFIG_CHARGING == CHARGING_CONTROL
851 if (charger_input_state == CHARGER_PLUGGED) {
852 pid_p = 0;
853 pid_i = 0;
854 snprintf(power_message, POWER_MESSAGE_LEN, "Charger plugged in");
856 * The charger was just plugged in. If the battery level is
857 * nearly charged, just trickle. If the battery is low, start
858 * a full charge cycle. If the battery level is in between,
859 * top-off and then trickle.
861 if(battery_percent > START_TOPOFF_CHG) {
862 powermgmt_last_cycle_level = battery_percent;
863 powermgmt_last_cycle_startstop_min = 0;
864 if(battery_percent >= START_TRICKLE_CHG) {
865 charge_state = TRICKLE;
866 target_voltage = TRICKLE_VOLTAGE;
867 } else {
868 charge_state = TOPOFF;
869 target_voltage = TOPOFF_VOLTAGE;
871 } else {
873 * Start the charger full strength
875 i = CHARGE_MAX_TIME_1500 * battery_capacity / 1500;
876 charge_max_time_idle =
877 i * (100 + 35 - battery_percent) / 100;
878 if (charge_max_time_idle > i) {
879 charge_max_time_idle = i;
881 charge_max_time_now = charge_max_time_idle;
883 snprintf(power_message, POWER_MESSAGE_LEN,
884 "ChgAt %d%% max %dm", battery_level(),
885 charge_max_time_now);
887 /* enable the charger after the max time calc is done,
888 because battery_level depends on if the charger is
889 on */
890 DEBUGF("power: charger inserted and battery"
891 " not full, charging\n");
892 powermgmt_last_cycle_level = battery_percent;
893 powermgmt_last_cycle_startstop_min = 0;
894 trickle_sec = 60;
895 long_delta = short_delta = 999999;
896 charge_state = CHARGING;
899 if (charge_state == CHARGING) {
900 /* alter charge time max length with extra disk use */
901 if (disk_activity_last_cycle) {
902 minutes_disk_activity++;
903 charge_max_time_now = charge_max_time_idle +
904 (minutes_disk_activity * 2 / 5);
905 disk_activity_last_cycle = false;
906 last_disk_activity = 0;
907 } else {
908 last_disk_activity++;
911 * Check the delta voltage over the last X minutes so we can do
912 * our end-of-charge logic based on the battery level change.
913 *(no longer use minimum time as logic for charge end has 50
914 * minutes minimum charge built in)
916 if (powermgmt_last_cycle_startstop_min > CHARGE_END_SHORTD) {
917 short_delta = power_history[0] -
918 power_history[CHARGE_END_SHORTD - 1];
921 if (powermgmt_last_cycle_startstop_min > CHARGE_END_LONGD) {
923 * Scan the history: the points where measurement is taken need to
924 * be fairly static. (check prior to short delta 'area')
925 * (also only check first and last 10 cycles - delta in middle OK)
927 long_delta = power_history[0] -
928 power_history[CHARGE_END_LONGD - 1];
930 for(i = CHARGE_END_SHORTD; i < CHARGE_END_SHORTD + 10; i++) {
931 if(((power_history[i] - power_history[i+1]) > 50) ||
932 ((power_history[i] - power_history[i+1]) < -50)) {
933 long_delta = 777777;
934 break;
937 for(i = CHARGE_END_LONGD - 11; i < CHARGE_END_LONGD - 1 ; i++) {
938 if(((power_history[i] - power_history[i+1]) > 50) ||
939 ((power_history[i] - power_history[i+1]) < -50)) {
940 long_delta = 888888;
941 break;
946 snprintf(power_message, POWER_MESSAGE_LEN,
947 "Chg %dm, max %dm", powermgmt_last_cycle_startstop_min,
948 charge_max_time_now);
950 * End of charge criteria (any qualify):
951 * 1) Charged a long time
952 * 2) DeltaV went negative for a short time ( & long delta static)
953 * 3) DeltaV was negative over a longer period (no disk use only)
954 * Note: short_delta and long_delta are millivolts
956 if ((powermgmt_last_cycle_startstop_min >= charge_max_time_now) ||
957 (short_delta <= -50 && long_delta < 50 ) || (long_delta < -20 &&
958 last_disk_activity > CHARGE_END_LONGD)) {
959 if (powermgmt_last_cycle_startstop_min > charge_max_time_now) {
960 DEBUGF("power: powermgmt_last_cycle_startstop_min > charge_max_time_now, "
961 "enough!\n");
963 *have charged too long and deltaV detection did not
964 *work!
966 snprintf(power_message, POWER_MESSAGE_LEN,
967 "Chg tmout %d min", charge_max_time_now);
969 * Switch to trickle charging. We skip the top-off
970 * since we've effectively done the top-off operation
971 * already since we charged for the maximum full
972 * charge time.
974 powermgmt_last_cycle_level = battery_percent;
975 powermgmt_last_cycle_startstop_min = 0;
976 charge_state = TRICKLE;
979 * set trickle charge target to a relative voltage instead
980 * of an arbitrary value - the fully charged voltage may
981 * vary according to ambient temp, battery condition etc
982 * trickle target is -0.15v from full voltage acheived
983 * topup target is -0.05v from full voltage
985 target_voltage = power_history[0] - 150;
987 } else {
988 if(short_delta <= -5) {
989 DEBUGF("power: short-term negative"
990 " delta, enough!\n");
991 snprintf(power_message, POWER_MESSAGE_LEN,
992 "end negd %d %dmin", short_delta,
993 powermgmt_last_cycle_startstop_min);
994 target_voltage = power_history[CHARGE_END_SHORTD - 1]
995 - 50;
996 } else {
997 DEBUGF("power: long-term small "
998 "positive delta, enough!\n");
999 snprintf(power_message, POWER_MESSAGE_LEN,
1000 "end lowd %d %dmin", long_delta,
1001 powermgmt_last_cycle_startstop_min);
1002 target_voltage = power_history[CHARGE_END_LONGD - 1]
1003 - 50;
1006 * Switch to top-off charging.
1008 powermgmt_last_cycle_level = battery_percent;
1009 powermgmt_last_cycle_startstop_min = 0;
1010 charge_state = TOPOFF;
1014 else if (charge_state != DISCHARGING) /* top off or trickle */
1017 *Time to switch from topoff to trickle?
1019 if ((charge_state == TOPOFF) &&
1020 (powermgmt_last_cycle_startstop_min > TOPOFF_MAX_TIME))
1022 powermgmt_last_cycle_level = battery_percent;
1023 powermgmt_last_cycle_startstop_min = 0;
1024 charge_state = TRICKLE;
1025 target_voltage = target_voltage - 100;
1028 * Adjust trickle charge time (proportional and integral terms).
1029 * Note: I considered setting the level higher if the USB is
1030 * plugged in, but it doesn't appear to be necessary and will
1031 * generate more heat [gvb].
1034 pid_p = ((signed)target_voltage - (signed)battery_millivolts) / 5;
1035 if((pid_p <= PID_DEADZONE) && (pid_p >= -PID_DEADZONE))
1036 pid_p = 0;
1038 if((unsigned) battery_millivolts < target_voltage) {
1039 if(pid_i < 60) {
1040 pid_i++; /* limit so it doesn't "wind up" */
1042 } else {
1043 if(pid_i > 0) {
1044 pid_i--; /* limit so it doesn't "wind up" */
1048 trickle_sec = pid_p + pid_i;
1050 if(trickle_sec > 60) {
1051 trickle_sec = 60;
1053 if(trickle_sec < 0) {
1054 trickle_sec = 0;
1057 } else if (charge_state == DISCHARGING) {
1058 trickle_sec = 0;
1060 * The charger is enabled here only in one case: if it was
1061 * turned on at boot time (power_init). Turn it off now.
1063 if (charger_enabled)
1064 charger_enable(false);
1067 if (charger_input_state == CHARGER_UNPLUGGED) {
1069 * The charger was just unplugged.
1071 DEBUGF("power: charger disconnected, disabling\n");
1073 charger_enable(false);
1074 powermgmt_last_cycle_level = battery_percent;
1075 powermgmt_last_cycle_startstop_min = 0;
1076 trickle_sec = 0;
1077 pid_p = 0;
1078 pid_i = 0;
1079 charge_state = DISCHARGING;
1080 snprintf(power_message, POWER_MESSAGE_LEN, "Charger: discharge");
1083 #endif /* CONFIG_CHARGING == CHARGING_CONTROL */
1085 /* sleep for a minute */
1087 #if CONFIG_CHARGING == CHARGING_CONTROL
1088 if(trickle_sec > 0) {
1089 charger_enable(true);
1090 power_thread_sleep(HZ * trickle_sec);
1092 if(trickle_sec < 60)
1093 charger_enable(false);
1094 power_thread_sleep(HZ * (60 - trickle_sec));
1095 #else
1096 power_thread_sleep(HZ * 60);
1097 #endif
1099 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1100 if(usb_inserted()) {
1101 if(fd >= 0) {
1102 /* It is probably too late to close the file but we can try...*/
1103 close(fd);
1104 fd = -1;
1106 } else {
1107 if(fd < 0) {
1108 fd = open(DEBUG_FILE_NAME, O_WRONLY | O_APPEND | O_CREAT);
1109 if(fd >= 0) {
1110 snprintf(debug_message, DEBUG_MESSAGE_LEN,
1111 "cycle_min, bat_millivolts, bat_percent, chgr_state, charge_state, pid_p, pid_i, trickle_sec\n");
1112 write(fd, debug_message, strlen(debug_message));
1113 wrcount = 99; /* force a flush */
1116 if(fd >= 0) {
1117 snprintf(debug_message, DEBUG_MESSAGE_LEN,
1118 "%d, %d, %d, %d, %d, %d, %d, %d\n",
1119 powermgmt_last_cycle_startstop_min, battery_millivolts,
1120 battery_percent, charger_input_state, charge_state,
1121 pid_p, pid_i, trickle_sec);
1122 write(fd, debug_message, strlen(debug_message));
1123 wrcount++;
1126 #endif
1127 handle_auto_poweroff();
1129 #if CONFIG_CHARGING == CHARGING_CONTROL
1130 powermgmt_last_cycle_startstop_min++;
1131 #endif
1135 void powermgmt_init(void)
1137 /* init history to 0 */
1138 memset(power_history, 0x00, sizeof(power_history));
1139 create_thread(power_thread, power_stack, sizeof(power_stack), 0,
1140 power_thread_name IF_PRIO(, PRIORITY_SYSTEM)
1141 IF_COP(, CPU));
1144 #endif /* SIMULATOR */
1146 void sys_poweroff(void)
1148 logf("sys_poweroff()");
1149 /* If the main thread fails to shut down the system, we will force a
1150 power off after an 20 second timeout - 28 seconds if recording */
1151 if (shutdown_timeout == 0)
1153 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1154 pcf50606_reset_timeout(); /* Reset timer on first attempt only */
1155 #endif
1156 #ifdef HAVE_RECORDING
1157 if (audio_status() & AUDIO_STATUS_RECORD)
1158 shutdown_timeout += HZ*8;
1159 #endif
1160 shutdown_timeout += HZ*20;
1163 queue_broadcast(SYS_POWEROFF, 0);
1166 void cancel_shutdown(void)
1168 logf("sys_cancel_shutdown()");
1170 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1171 /* TODO: Move some things to target/ tree */
1172 if (shutdown_timeout)
1173 pcf50606_reset_timeout();
1174 #endif
1176 shutdown_timeout = 0;
1179 /* Various hardware housekeeping tasks relating to shutting down the jukebox */
1180 void shutdown_hw(void)
1182 #ifndef SIMULATOR
1183 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1184 if(fd >= 0) {
1185 close(fd);
1186 fd = -1;
1188 #endif
1189 audio_stop();
1190 if (battery_level_safe()) { /* do not save on critical battery */
1191 #ifdef HAVE_LCD_BITMAP
1192 glyph_cache_save();
1193 #endif
1194 if(ata_disk_is_active())
1195 ata_spindown(1);
1197 while(ata_disk_is_active())
1198 sleep(HZ/10);
1200 #if CONFIG_CODEC != SWCODEC
1201 mp3_shutdown();
1202 #else
1203 audiohw_close();
1204 #endif
1206 /* If HD is still active we try to wait for spindown, otherwise the
1207 shutdown_timeout in power_thread_sleep will force a power off */
1208 while(ata_disk_is_active())
1209 sleep(HZ/10);
1210 #ifndef IAUDIO_X5
1211 lcd_set_contrast(0);
1212 #endif /* IAUDIO_X5 */
1213 #ifdef HAVE_REMOTE_LCD
1214 lcd_remote_set_contrast(0);
1215 #endif
1217 #ifdef HAVE_LCD_SHUTDOWN
1218 lcd_shutdown();
1219 #endif
1221 /* Small delay to make sure all HW gets time to flush. Especially
1222 eeprom chips are quite slow and might be still writing the last
1223 byte. */
1224 sleep(HZ/4);
1225 power_off();
1226 #endif /* #ifndef SIMULATOR */
1229 /* Send system battery level update events on reaching certain significant
1230 levels. This must be called after battery_percent has been updated. */
1231 static void send_battery_level_event(void)
1233 static const int levels[] = { 5, 15, 30, 50, 0 };
1234 const int *level = levels;
1235 while (*level)
1237 if (battery_percent <= *level && last_sent_battery_level > *level)
1239 last_sent_battery_level = *level;
1240 queue_broadcast(SYS_BATTERY_UPDATE, last_sent_battery_level);
1241 break;
1243 level++;