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 #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
205 char power_message
[POWER_MESSAGE_LEN
] = ""; /* message that's shown in
207 /* percentage at which charging
209 int powermgmt_last_cycle_startstop_min
= 0; /* how many minutes ago was the
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
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 */
232 #define BATT_AVE_SAMPLES 128 /* slw filter constant for all others */
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;
241 #define battery_type 0
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();
267 *voltage
= millivolts
;
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
) {
283 battery_status_update(); /* recalculate the battery status */
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
)
329 sleeptimer_active
= true;
330 sleeptimer_endtick
= current_tick
+ seconds
* HZ
;
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
;
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])
352 if (voltage
>= table
[10])
355 /* search nearest value */
357 while ((i
< 10) && (table
[i
+1] < voltage
))
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
)
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 */
415 /* always use the discharge table */
416 level
= voltage_to_percent(battery_millivolts
,
417 percent_to_volt_discharge
[battery_type
]);
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());
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;
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
452 level
= (level
* 80) / 100;
453 if (level
> 72) { /* > 91% */
454 int i
= POWER_HISTORY_LEN
;
456 #ifdef HAVE_CHARGE_STATE
457 if (charge_state
== DISCHARGING
)
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 */
470 powermgmt_est_runningtime_min
= battery_capacity
* 60
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 powermgmt_est_runningtime_min
= (battery_millivolts
-
483 battery_level_shutoff
[0]) / 2;
486 battery_percent
= level
;
487 send_battery_level_event();
491 * We shut off in the following cases:
492 * 1) The unit is idle, not playing music
493 * 2) The unit is playing music, but is paused
494 * 3) The battery level has reached shutdown limit
496 * We do not shut off in the following cases:
497 * 1) The USB is connected
498 * 2) The charger is connected
499 * 3) We are recording, or recording with pause
500 * 4) The radio is playing
502 static void handle_auto_poweroff(void)
504 long timeout
= poweroff_timeout
*60*HZ
;
505 int audio_stat
= audio_status();
509 * Inhibit shutdown as long as the charger is plugged in. If it is
510 * unplugged, wait for a timeout period and then shut down.
512 if(charger_input_state
== CHARGER
|| audio_stat
== AUDIO_STATUS_PLAY
) {
513 last_event_tick
= current_tick
;
517 #ifndef NO_LOW_BATTERY_SHUTDOWN
518 /* switch off unit if battery level is too low for reliable operation */
519 if(battery_millivolts
< battery_level_shutoff
[battery_type
]) {
520 if(!shutdown_timeout
) {
528 #if CONFIG_TUNER && !defined(BOOTLOADER)
529 (!(get_radio_status() & FMRADIO_PLAYING
)) &&
532 ((audio_stat
== 0) ||
533 ((audio_stat
== (AUDIO_STATUS_PLAY
| AUDIO_STATUS_PAUSE
)) &&
534 !sleeptimer_active
)))
536 if(TIME_AFTER(current_tick
, last_event_tick
+ timeout
) &&
537 TIME_AFTER(current_tick
, last_disk_activity
+ timeout
))
544 /* Handle sleeptimer */
545 if(sleeptimer_active
&& !usb_inserted())
547 if(TIME_AFTER(current_tick
, sleeptimer_endtick
))
550 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
551 if((charger_input_state
== CHARGER
) ||
552 (charger_input_state
== CHARGER_PLUGGED
))
554 DEBUGF("Sleep timer timeout. Stopping...\n");
556 backlight_off(); /* Nighty, nighty... */
561 DEBUGF("Sleep timer timeout. Shutting off...\n");
570 * Estimate how much current we are drawing just to run.
572 static int runcurrent(void)
576 #if MEM == 8 && !defined(HAVE_MMC)
577 /* assuming 192 kbps, the running time is 22% longer with 8MB */
578 current
= (CURRENT_NORMAL
*100/122);
580 current
= CURRENT_NORMAL
;
581 #endif /* MEM == 8 */
584 #if defined(HAVE_USB_POWER)
585 #if (CURRENT_USB < CURRENT_NORMAL)
593 current
= CURRENT_USB
;
596 #if defined(HAVE_BACKLIGHT) && !defined(BOOTLOADER)
597 if (backlight_get_current_timeout() == 0) /* LED always on */
598 current
+= CURRENT_BACKLIGHT
;
601 #if defined(HAVE_RECORDING) && defined(CURRENT_RECORD)
602 if (audio_status() & AUDIO_STATUS_RECORD
)
603 current
+= CURRENT_RECORD
;
606 #ifdef HAVE_SPDIF_POWER
608 current
+= CURRENT_SPDIF_OUT
;
611 #ifdef HAVE_REMOTE_LCD
613 current
+= CURRENT_REMOTE
;
620 /* Check to see whether or not we've received an alarm in the last second */
621 #ifdef HAVE_RTC_ALARM
622 static void power_thread_rtc_process(void)
624 if (rtc_check_alarm_flag()) {
625 rtc_enable_alarm(false);
631 * This function is called to do the relativly long sleep waits from within the
632 * main power_thread loop while at the same time servicing any other periodic
633 * functions in the power thread which need to be called at a faster periodic
634 * rate than the slow periodic rate of the main power_thread loop.
636 * While we are waiting for the time to expire, we average the battery
639 static void power_thread_sleep(int ticks
)
647 * Detect charger plugged/unplugged transitions. On a plugged or
648 * unplugged event, we return immediately, run once through the main
649 * loop (including the subroutines), and end up back here where we
650 * transition to the appropriate steady state charger on/off state.
652 if(charger_inserted()
653 #ifdef HAVE_USB_POWER /* USB powered or USB inserted both provide power */
656 || (usb_inserted() && usb_charging_enabled())
660 switch(charger_input_state
) {
662 case CHARGER_UNPLUGGED
:
663 charger_input_state
= CHARGER_PLUGGED
;
665 case CHARGER_PLUGGED
:
666 queue_broadcast(SYS_CHARGER_CONNECTED
, 0);
667 last_sent_battery_level
= 0;
668 charger_input_state
= CHARGER
;
673 } else { /* charger not inserted */
674 switch(charger_input_state
) {
677 case CHARGER_UNPLUGGED
:
678 queue_broadcast(SYS_CHARGER_DISCONNECTED
, 0);
679 last_sent_battery_level
= 100;
680 charger_input_state
= NO_CHARGER
;
682 case CHARGER_PLUGGED
:
684 charger_input_state
= CHARGER_UNPLUGGED
;
689 #if CONFIG_CHARGING == CHARGING_MONITOR
690 switch (charger_input_state
) {
691 case CHARGER_UNPLUGGED
:
693 charge_state
= DISCHARGING
;
695 case CHARGER_PLUGGED
:
697 if (charging_state()) {
698 charge_state
= CHARGING
;
700 charge_state
= DISCHARGING
;
705 #endif /* CONFIG_CHARGING == CHARGING_MONITOR */
707 small_ticks
= MIN(HZ
/2, ticks
);
709 ticks
-= small_ticks
;
711 /* If the power off timeout expires, the main thread has failed
712 to shut down the system, and we need to force a power off */
713 if(shutdown_timeout
) {
714 shutdown_timeout
-= small_ticks
;
715 if(shutdown_timeout
<= 0)
719 #ifdef HAVE_RTC_ALARM
720 power_thread_rtc_process();
724 * Do a digital exponential filter. We don't sample the battery if
725 * the disk is spinning unless we are in USB mode (the disk will most
726 * likely always be spinning in USB mode).
728 if (!ata_disk_is_active() || usb_inserted()) {
729 avgbat
+= battery_adc_voltage() - (avgbat
/ BATT_AVE_SAMPLES
);
731 * battery_millivolts is the millivolt-scaled filtered battery value.
733 battery_millivolts
= avgbat
/ BATT_AVE_SAMPLES
;
735 /* update battery status every time an update is available */
736 battery_status_update();
738 else if (battery_percent
< 8) {
739 /* If battery is low, observe voltage during disk activity.
740 * Shut down if voltage drops below shutoff level and we are not
741 * using NiMH or Alkaline batteries.
743 battery_millivolts
= (battery_adc_voltage() +
744 battery_millivolts
+ 1) / 2;
746 /* update battery status every time an update is available */
747 battery_status_update();
749 #ifndef NO_LOW_BATTERY_SHUTDOWN
750 if (!shutdown_timeout
&&
751 (battery_millivolts
< battery_level_shutoff
[battery_type
]))
755 avgbat
+= battery_millivolts
- (avgbat
/ BATT_AVE_SAMPLES
);
758 #if CONFIG_CHARGING == CHARGING_CONTROL
759 if (ata_disk_is_active()) {
760 /* flag hdd use for charging calculation */
761 disk_activity_last_cycle
= true;
764 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
766 * If we have a lot of pending writes or if the disk is spining,
767 * fsync the debug log file.
769 if((wrcount
> 10) || ((wrcount
> 0) && ata_disk_is_active())) {
779 * This power thread maintains a history of battery voltage
780 * and implements a charging algorithm.
781 * For a complete description of the charging algorithm read
782 * docs/CHARGING_ALGORITHM.
785 static void power_thread(void)
787 #if CONFIG_CHARGING == CHARGING_CONTROL
789 unsigned int target_voltage
= TRICKLE_VOLTAGE
; /* desired topoff/trickle
791 int charge_max_time_idle
= 0; /* max. charging duration, calculated at
792 * beginning of charging */
793 int charge_max_time_now
= 0; /* max. charging duration including
795 int minutes_disk_activity
= 0; /* count minutes of hdd use during
797 int last_disk_activity
= CHARGE_END_LONGD
+ 1; /* last hdd use x mins ago */
800 /* Delay reading the first battery level */
802 while(battery_adc_voltage()>4200) /* gives false readings initially */
806 /* initialize the voltages for the exponential filter */
807 avgbat
= battery_adc_voltage() + 15;
809 #ifndef HAVE_MMC /* this adjustment is only needed for HD based */
810 /* The battery voltage is usually a little lower directly after
811 turning on, because the disk was used heavily. Raise it by 5% */
813 if(!charger_inserted()) /* only if charger not connected */
815 avgbat
+= (percent_to_volt_discharge
[battery_type
][6] -
816 percent_to_volt_discharge
[battery_type
][5]) / 2;
817 #endif /* not HAVE_MMC */
819 avgbat
= avgbat
* BATT_AVE_SAMPLES
;
820 battery_millivolts
= avgbat
/ BATT_AVE_SAMPLES
;
823 if(charger_inserted()) {
824 battery_percent
= voltage_to_percent(battery_millivolts
,
825 percent_to_volt_charge
);
826 #if defined(IRIVER_H100_SERIES) || defined(IRIVER_H300_SERIES)
827 /* Checking for iriver is a temporary kludge. */
828 charger_input_state
= CHARGER
;
832 { battery_percent
= voltage_to_percent(battery_millivolts
,
833 percent_to_volt_discharge
[battery_type
]);
834 battery_percent
+= (battery_percent
< 100);
837 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
844 /* rotate the power history */
845 memmove(power_history
+ 1, power_history
,
846 sizeof(power_history
) - sizeof(power_history
[0]));
848 /* insert new value at the start, in millivolts 8-) */
849 power_history
[0] = battery_millivolts
;
851 #if CONFIG_CHARGING == CHARGING_CONTROL
852 if (charger_input_state
== CHARGER_PLUGGED
) {
855 snprintf(power_message
, POWER_MESSAGE_LEN
, "Charger plugged in");
857 * The charger was just plugged in. If the battery level is
858 * nearly charged, just trickle. If the battery is low, start
859 * a full charge cycle. If the battery level is in between,
860 * top-off and then trickle.
862 if(battery_percent
> START_TOPOFF_CHG
) {
863 powermgmt_last_cycle_level
= battery_percent
;
864 powermgmt_last_cycle_startstop_min
= 0;
865 if(battery_percent
>= START_TRICKLE_CHG
) {
866 charge_state
= TRICKLE
;
867 target_voltage
= TRICKLE_VOLTAGE
;
869 charge_state
= TOPOFF
;
870 target_voltage
= TOPOFF_VOLTAGE
;
874 * Start the charger full strength
876 i
= CHARGE_MAX_TIME_1500
* battery_capacity
/ 1500;
877 charge_max_time_idle
=
878 i
* (100 + 35 - battery_percent
) / 100;
879 if (charge_max_time_idle
> i
) {
880 charge_max_time_idle
= i
;
882 charge_max_time_now
= charge_max_time_idle
;
884 snprintf(power_message
, POWER_MESSAGE_LEN
,
885 "ChgAt %d%% max %dm", battery_level(),
886 charge_max_time_now
);
888 /* enable the charger after the max time calc is done,
889 because battery_level depends on if the charger is
891 DEBUGF("power: charger inserted and battery"
892 " not full, charging\n");
893 powermgmt_last_cycle_level
= battery_percent
;
894 powermgmt_last_cycle_startstop_min
= 0;
896 long_delta
= short_delta
= 999999;
897 charge_state
= CHARGING
;
900 if (charge_state
== CHARGING
) {
901 /* alter charge time max length with extra disk use */
902 if (disk_activity_last_cycle
) {
903 minutes_disk_activity
++;
904 charge_max_time_now
= charge_max_time_idle
+
905 (minutes_disk_activity
* 2 / 5);
906 disk_activity_last_cycle
= false;
907 last_disk_activity
= 0;
909 last_disk_activity
++;
912 * Check the delta voltage over the last X minutes so we can do
913 * our end-of-charge logic based on the battery level change.
914 *(no longer use minimum time as logic for charge end has 50
915 * minutes minimum charge built in)
917 if (powermgmt_last_cycle_startstop_min
> CHARGE_END_SHORTD
) {
918 short_delta
= power_history
[0] -
919 power_history
[CHARGE_END_SHORTD
- 1];
922 if (powermgmt_last_cycle_startstop_min
> CHARGE_END_LONGD
) {
924 * Scan the history: the points where measurement is taken need to
925 * be fairly static. (check prior to short delta 'area')
926 * (also only check first and last 10 cycles - delta in middle OK)
928 long_delta
= power_history
[0] -
929 power_history
[CHARGE_END_LONGD
- 1];
931 for(i
= CHARGE_END_SHORTD
; i
< CHARGE_END_SHORTD
+ 10; i
++) {
932 if(((power_history
[i
] - power_history
[i
+1]) > 50) ||
933 ((power_history
[i
] - power_history
[i
+1]) < -50)) {
938 for(i
= CHARGE_END_LONGD
- 11; i
< CHARGE_END_LONGD
- 1 ; i
++) {
939 if(((power_history
[i
] - power_history
[i
+1]) > 50) ||
940 ((power_history
[i
] - power_history
[i
+1]) < -50)) {
947 snprintf(power_message
, POWER_MESSAGE_LEN
,
948 "Chg %dm, max %dm", powermgmt_last_cycle_startstop_min
,
949 charge_max_time_now
);
951 * End of charge criteria (any qualify):
952 * 1) Charged a long time
953 * 2) DeltaV went negative for a short time ( & long delta static)
954 * 3) DeltaV was negative over a longer period (no disk use only)
955 * Note: short_delta and long_delta are millivolts
957 if ((powermgmt_last_cycle_startstop_min
>= charge_max_time_now
) ||
958 (short_delta
<= -50 && long_delta
< 50 ) || (long_delta
< -20 &&
959 last_disk_activity
> CHARGE_END_LONGD
)) {
960 if (powermgmt_last_cycle_startstop_min
> charge_max_time_now
) {
961 DEBUGF("power: powermgmt_last_cycle_startstop_min > charge_max_time_now, "
964 *have charged too long and deltaV detection did not
967 snprintf(power_message
, POWER_MESSAGE_LEN
,
968 "Chg tmout %d min", charge_max_time_now
);
970 * Switch to trickle charging. We skip the top-off
971 * since we've effectively done the top-off operation
972 * already since we charged for the maximum full
975 powermgmt_last_cycle_level
= battery_percent
;
976 powermgmt_last_cycle_startstop_min
= 0;
977 charge_state
= TRICKLE
;
980 * set trickle charge target to a relative voltage instead
981 * of an arbitrary value - the fully charged voltage may
982 * vary according to ambient temp, battery condition etc
983 * trickle target is -0.15v from full voltage acheived
984 * topup target is -0.05v from full voltage
986 target_voltage
= power_history
[0] - 150;
989 if(short_delta
<= -5) {
990 DEBUGF("power: short-term negative"
991 " delta, enough!\n");
992 snprintf(power_message
, POWER_MESSAGE_LEN
,
993 "end negd %d %dmin", short_delta
,
994 powermgmt_last_cycle_startstop_min
);
995 target_voltage
= power_history
[CHARGE_END_SHORTD
- 1]
998 DEBUGF("power: long-term small "
999 "positive delta, enough!\n");
1000 snprintf(power_message
, POWER_MESSAGE_LEN
,
1001 "end lowd %d %dmin", long_delta
,
1002 powermgmt_last_cycle_startstop_min
);
1003 target_voltage
= power_history
[CHARGE_END_LONGD
- 1]
1007 * Switch to top-off charging.
1009 powermgmt_last_cycle_level
= battery_percent
;
1010 powermgmt_last_cycle_startstop_min
= 0;
1011 charge_state
= TOPOFF
;
1015 else if (charge_state
!= DISCHARGING
) /* top off or trickle */
1018 *Time to switch from topoff to trickle?
1020 if ((charge_state
== TOPOFF
) &&
1021 (powermgmt_last_cycle_startstop_min
> TOPOFF_MAX_TIME
))
1023 powermgmt_last_cycle_level
= battery_percent
;
1024 powermgmt_last_cycle_startstop_min
= 0;
1025 charge_state
= TRICKLE
;
1026 target_voltage
= target_voltage
- 100;
1029 * Adjust trickle charge time (proportional and integral terms).
1030 * Note: I considered setting the level higher if the USB is
1031 * plugged in, but it doesn't appear to be necessary and will
1032 * generate more heat [gvb].
1035 pid_p
= ((signed)target_voltage
- (signed)battery_millivolts
) / 5;
1036 if((pid_p
<= PID_DEADZONE
) && (pid_p
>= -PID_DEADZONE
))
1039 if((unsigned) battery_millivolts
< target_voltage
) {
1041 pid_i
++; /* limit so it doesn't "wind up" */
1045 pid_i
--; /* limit so it doesn't "wind up" */
1049 trickle_sec
= pid_p
+ pid_i
;
1051 if(trickle_sec
> 60) {
1054 if(trickle_sec
< 0) {
1058 } else if (charge_state
== DISCHARGING
) {
1061 * The charger is enabled here only in one case: if it was
1062 * turned on at boot time (power_init). Turn it off now.
1064 if (charger_enabled
)
1065 charger_enable(false);
1068 if (charger_input_state
== CHARGER_UNPLUGGED
) {
1070 * The charger was just unplugged.
1072 DEBUGF("power: charger disconnected, disabling\n");
1074 charger_enable(false);
1075 powermgmt_last_cycle_level
= battery_percent
;
1076 powermgmt_last_cycle_startstop_min
= 0;
1080 charge_state
= DISCHARGING
;
1081 snprintf(power_message
, POWER_MESSAGE_LEN
, "Charger: discharge");
1084 #endif /* CONFIG_CHARGING == CHARGING_CONTROL */
1086 /* sleep for a minute */
1088 #if CONFIG_CHARGING == CHARGING_CONTROL
1089 if(trickle_sec
> 0) {
1090 charger_enable(true);
1091 power_thread_sleep(HZ
* trickle_sec
);
1093 if(trickle_sec
< 60)
1094 charger_enable(false);
1095 power_thread_sleep(HZ
* (60 - trickle_sec
));
1097 power_thread_sleep(HZ
* 60);
1100 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1101 if(usb_inserted()) {
1103 /* It is probably too late to close the file but we can try...*/
1109 fd
= open(DEBUG_FILE_NAME
, O_WRONLY
| O_APPEND
| O_CREAT
);
1111 snprintf(debug_message
, DEBUG_MESSAGE_LEN
,
1112 "cycle_min, bat_millivolts, bat_percent, chgr_state, charge_state, pid_p, pid_i, trickle_sec\n");
1113 write(fd
, debug_message
, strlen(debug_message
));
1114 wrcount
= 99; /* force a flush */
1118 snprintf(debug_message
, DEBUG_MESSAGE_LEN
,
1119 "%d, %d, %d, %d, %d, %d, %d, %d\n",
1120 powermgmt_last_cycle_startstop_min
, battery_millivolts
,
1121 battery_percent
, charger_input_state
, charge_state
,
1122 pid_p
, pid_i
, trickle_sec
);
1123 write(fd
, debug_message
, strlen(debug_message
));
1128 handle_auto_poweroff();
1130 #if CONFIG_CHARGING == CHARGING_CONTROL
1131 powermgmt_last_cycle_startstop_min
++;
1136 void powermgmt_init(void)
1138 /* init history to 0 */
1139 memset(power_history
, 0x00, sizeof(power_history
));
1140 create_thread(power_thread
, power_stack
, sizeof(power_stack
), 0,
1141 power_thread_name
IF_PRIO(, PRIORITY_SYSTEM
)
1145 #endif /* SIMULATOR */
1147 void sys_poweroff(void)
1149 logf("sys_poweroff()");
1150 /* If the main thread fails to shut down the system, we will force a
1151 power off after an 20 second timeout - 28 seconds if recording */
1152 if (shutdown_timeout
== 0)
1154 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1155 pcf50606_reset_timeout(); /* Reset timer on first attempt only */
1157 #ifdef HAVE_RECORDING
1158 if (audio_status() & AUDIO_STATUS_RECORD
)
1159 shutdown_timeout
+= HZ
*8;
1161 shutdown_timeout
+= HZ
*20;
1164 queue_broadcast(SYS_POWEROFF
, 0);
1167 void cancel_shutdown(void)
1169 logf("sys_cancel_shutdown()");
1171 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1172 /* TODO: Move some things to target/ tree */
1173 if (shutdown_timeout
)
1174 pcf50606_reset_timeout();
1177 shutdown_timeout
= 0;
1180 /* Various hardware housekeeping tasks relating to shutting down the jukebox */
1181 void shutdown_hw(void)
1184 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1191 if (battery_level_safe()) { /* do not save on critical battery */
1192 #ifdef HAVE_LCD_BITMAP
1195 if(ata_disk_is_active())
1198 while(ata_disk_is_active())
1201 #if CONFIG_CODEC != SWCODEC
1207 /* If HD is still active we try to wait for spindown, otherwise the
1208 shutdown_timeout in power_thread_sleep will force a power off */
1209 while(ata_disk_is_active())
1212 lcd_set_contrast(0);
1213 #endif /* IAUDIO_X5 */
1214 #ifdef HAVE_REMOTE_LCD
1215 lcd_remote_set_contrast(0);
1218 #ifdef HAVE_LCD_SHUTDOWN
1222 /* Small delay to make sure all HW gets time to flush. Especially
1223 eeprom chips are quite slow and might be still writing the last
1227 #endif /* #ifndef SIMULATOR */
1230 /* Send system battery level update events on reaching certain significant
1231 levels. This must be called after battery_percent has been updated. */
1232 static void send_battery_level_event(void)
1234 static const int levels
[] = { 5, 15, 30, 50, 0 };
1235 const int *level
= levels
;
1238 if (battery_percent
<= *level
&& last_sent_battery_level
> *level
)
1240 last_sent_battery_level
= *level
;
1241 queue_broadcast(SYS_BATTERY_UPDATE
, last_sent_battery_level
);