1 /***************************************************************************
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
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 ****************************************************************************/
34 #include "mp3_playback.h"
36 #include "powermgmt.h"
37 #include "backlight.h"
44 #ifdef HAVE_LCD_BITMAP
47 #if defined(HAVE_RECORDING) && (CONFIG_CODEC == SWCODEC)
48 #include "pcm_record.h"
51 #include "lcd-remote.h"
56 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
58 #include "lcd-remote-target.h"
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.
66 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
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 */
78 static int shutdown_timeout
= 0;
79 #if CONFIG_CHARGING >= CHARGING_MONITOR
80 charge_state_type charge_state
; /* charging mode */
83 static void send_battery_level_event(void);
84 static int last_sent_battery_level
= 100;
87 charger_input_state_type charger_input_state IDATA_ATTR
;
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;
107 if (last_change
< now
)
111 /* change the values: */
114 if (battery_millivolts
>= BATT_MAXMVOLT
)
116 /* Pretend the charger was disconnected */
118 queue_broadcast(SYS_CHARGER_DISCONNECTED
, 0);
119 last_sent_battery_level
= 100;
124 if (battery_millivolts
<= BATT_MINMVOLT
)
126 /* Pretend the charger was connected */
128 queue_broadcast(SYS_CHARGER_CONNECTED
, 0);
129 last_sent_battery_level
= 0;
133 battery_millivolts
+= (BATT_MAXMVOLT
- BATT_MINMVOLT
) / 50;
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();
148 *voltage
= battery_millivolts
;
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
)
182 void set_battery_capacity(int capacity
)
187 #if BATTERY_TYPES_COUNT > 1
188 void set_battery_type(int type
)
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
210 char power_message
[POWER_MESSAGE_LEN
] = ""; /* message that's shown in
212 /* percentage at which charging
214 int powermgmt_last_cycle_startstop_min
= 0; /* how many minutes ago was the
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
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 */
237 #define BATT_AVE_SAMPLES 128 /* slw filter constant for all others */
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;
246 #define battery_type 0
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();
272 *voltage
= millivolts
;
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
) {
288 battery_status_update(); /* recalculate the battery status */
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
)
334 sleeptimer_active
= true;
335 sleeptimer_endtick
= current_tick
+ seconds
* HZ
;
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
;
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])
357 if (voltage
>= table
[10])
360 /* search nearest value */
362 while ((i
< 10) && (table
[i
+1] < voltage
))
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
)
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 */
420 /* always use the discharge table */
421 level
= voltage_to_percent(battery_millivolts
,
422 percent_to_volt_discharge
[battery_type
]);
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());
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;
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
457 level
= (level
* 80) / 100;
458 if (level
> 72) { /* > 91% */
459 int i
= POWER_HISTORY_LEN
;
461 #ifdef HAVE_CHARGE_STATE
462 if (charge_state
== DISCHARGING
)
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 */
475 powermgmt_est_runningtime_min
= battery_capacity
* 60
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();
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();
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
;
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
) {
533 #if CONFIG_TUNER && !defined(BOOTLOADER)
534 (!(get_radio_status() & FMRADIO_PLAYING
)) &&
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
))
549 /* Handle sleeptimer */
550 if(sleeptimer_active
&& !usb_inserted())
552 if(TIME_AFTER(current_tick
, sleeptimer_endtick
))
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");
561 backlight_off(); /* Nighty, nighty... */
566 DEBUGF("Sleep timer timeout. Shutting off...\n");
575 * Estimate how much current we are drawing just to run.
577 static int runcurrent(void)
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);
585 current
= CURRENT_NORMAL
;
586 #endif /* MEM == 8 */
589 #if defined(HAVE_USB_POWER)
590 #if (CURRENT_USB < CURRENT_NORMAL)
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
;
606 #if defined(HAVE_RECORDING) && defined(CURRENT_RECORD)
607 if (audio_status() & AUDIO_STATUS_RECORD
)
608 current
+= CURRENT_RECORD
;
611 #ifdef HAVE_SPDIF_POWER
613 current
+= CURRENT_SPDIF_OUT
;
616 #ifdef HAVE_REMOTE_LCD
618 current
+= CURRENT_REMOTE
;
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);
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
644 static void power_thread_sleep(int ticks
)
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 */
661 || (usb_inserted() && usb_charging_enabled())
665 switch(charger_input_state
) {
667 case CHARGER_UNPLUGGED
:
668 charger_input_state
= CHARGER_PLUGGED
;
670 case CHARGER_PLUGGED
:
671 queue_broadcast(SYS_CHARGER_CONNECTED
, 0);
672 last_sent_battery_level
= 0;
673 charger_input_state
= CHARGER
;
678 } else { /* charger not inserted */
679 switch(charger_input_state
) {
682 case CHARGER_UNPLUGGED
:
683 queue_broadcast(SYS_CHARGER_DISCONNECTED
, 0);
684 last_sent_battery_level
= 100;
685 charger_input_state
= NO_CHARGER
;
687 case CHARGER_PLUGGED
:
689 charger_input_state
= CHARGER_UNPLUGGED
;
694 #if CONFIG_CHARGING == CHARGING_MONITOR
695 switch (charger_input_state
) {
696 case CHARGER_UNPLUGGED
:
698 charge_state
= DISCHARGING
;
700 case CHARGER_PLUGGED
:
702 if (charging_state()) {
703 charge_state
= CHARGING
;
705 charge_state
= DISCHARGING
;
710 #endif /* CONFIG_CHARGING == CHARGING_MONITOR */
712 small_ticks
= MIN(HZ
/2, 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)
724 #ifdef HAVE_RTC_ALARM
725 power_thread_rtc_process();
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
]))
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;
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())) {
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
794 unsigned int target_voltage
= TRICKLE_VOLTAGE
; /* desired topoff/trickle
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
800 int minutes_disk_activity
= 0; /* count minutes of hdd use during
802 int last_disk_activity
= CHARGE_END_LONGD
+ 1; /* last hdd use x mins ago */
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% */
812 if(!charger_inserted()) /* only if charger not connected */
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
;
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
;
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)
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
) {
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
;
868 charge_state
= TOPOFF
;
869 target_voltage
= TOPOFF_VOLTAGE
;
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
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;
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;
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)) {
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)) {
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, "
963 *have charged too long and deltaV detection did not
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
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;
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]
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]
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
))
1038 if((unsigned) battery_millivolts
< target_voltage
) {
1040 pid_i
++; /* limit so it doesn't "wind up" */
1044 pid_i
--; /* limit so it doesn't "wind up" */
1048 trickle_sec
= pid_p
+ pid_i
;
1050 if(trickle_sec
> 60) {
1053 if(trickle_sec
< 0) {
1057 } else if (charge_state
== DISCHARGING
) {
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;
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
));
1096 power_thread_sleep(HZ
* 60);
1099 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1100 if(usb_inserted()) {
1102 /* It is probably too late to close the file but we can try...*/
1108 fd
= open(DEBUG_FILE_NAME
, O_WRONLY
| O_APPEND
| O_CREAT
);
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 */
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
));
1127 handle_auto_poweroff();
1129 #if CONFIG_CHARGING == CHARGING_CONTROL
1130 powermgmt_last_cycle_startstop_min
++;
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
)
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 */
1156 #ifdef HAVE_RECORDING
1157 if (audio_status() & AUDIO_STATUS_RECORD
)
1158 shutdown_timeout
+= HZ
*8;
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();
1176 shutdown_timeout
= 0;
1179 /* Various hardware housekeeping tasks relating to shutting down the jukebox */
1180 void shutdown_hw(void)
1183 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1190 if (battery_level_safe()) { /* do not save on critical battery */
1191 #ifdef HAVE_LCD_BITMAP
1194 if(ata_disk_is_active())
1197 while(ata_disk_is_active())
1200 #if CONFIG_CODEC != SWCODEC
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())
1211 lcd_set_contrast(0);
1212 #endif /* IAUDIO_X5 */
1213 #ifdef HAVE_REMOTE_LCD
1214 lcd_remote_set_contrast(0);
1217 #ifdef HAVE_LCD_SHUTDOWN
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
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
;
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
);