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 */
803 /* initialize the voltages for the exponential filter */
804 avgbat
= battery_adc_voltage() + 15;
806 #ifndef HAVE_MMC /* this adjustment is only needed for HD based */
807 /* The battery voltage is usually a little lower directly after
808 turning on, because the disk was used heavily. Raise it by 5% */
810 if(!charger_inserted()) /* only if charger not connected */
812 avgbat
+= (percent_to_volt_discharge
[battery_type
][6] -
813 percent_to_volt_discharge
[battery_type
][5]) / 2;
814 #endif /* not HAVE_MMC */
816 avgbat
= avgbat
* BATT_AVE_SAMPLES
;
817 battery_millivolts
= avgbat
/ BATT_AVE_SAMPLES
;
820 if(charger_inserted()) {
821 battery_percent
= voltage_to_percent(battery_millivolts
,
822 percent_to_volt_charge
);
823 #if defined(IRIVER_H100_SERIES) || defined(IRIVER_H300_SERIES)
824 /* Checking for iriver is a temporary kludge. */
825 charger_input_state
= CHARGER
;
829 { battery_percent
= voltage_to_percent(battery_millivolts
,
830 percent_to_volt_discharge
[battery_type
]);
831 battery_percent
+= (battery_percent
< 100);
834 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
841 /* rotate the power history */
842 memmove(power_history
+ 1, power_history
,
843 sizeof(power_history
) - sizeof(power_history
[0]));
845 /* insert new value at the start, in millivolts 8-) */
846 power_history
[0] = battery_millivolts
;
848 #if CONFIG_CHARGING == CHARGING_CONTROL
849 if (charger_input_state
== CHARGER_PLUGGED
) {
852 snprintf(power_message
, POWER_MESSAGE_LEN
, "Charger plugged in");
854 * The charger was just plugged in. If the battery level is
855 * nearly charged, just trickle. If the battery is low, start
856 * a full charge cycle. If the battery level is in between,
857 * top-off and then trickle.
859 if(battery_percent
> START_TOPOFF_CHG
) {
860 powermgmt_last_cycle_level
= battery_percent
;
861 powermgmt_last_cycle_startstop_min
= 0;
862 if(battery_percent
>= START_TRICKLE_CHG
) {
863 charge_state
= TRICKLE
;
864 target_voltage
= TRICKLE_VOLTAGE
;
866 charge_state
= TOPOFF
;
867 target_voltage
= TOPOFF_VOLTAGE
;
871 * Start the charger full strength
873 i
= CHARGE_MAX_TIME_1500
* battery_capacity
/ 1500;
874 charge_max_time_idle
=
875 i
* (100 + 35 - battery_percent
) / 100;
876 if (charge_max_time_idle
> i
) {
877 charge_max_time_idle
= i
;
879 charge_max_time_now
= charge_max_time_idle
;
881 snprintf(power_message
, POWER_MESSAGE_LEN
,
882 "ChgAt %d%% max %dm", battery_level(),
883 charge_max_time_now
);
885 /* enable the charger after the max time calc is done,
886 because battery_level depends on if the charger is
888 DEBUGF("power: charger inserted and battery"
889 " not full, charging\n");
890 powermgmt_last_cycle_level
= battery_percent
;
891 powermgmt_last_cycle_startstop_min
= 0;
893 long_delta
= short_delta
= 999999;
894 charge_state
= CHARGING
;
897 if (charge_state
== CHARGING
) {
898 /* alter charge time max length with extra disk use */
899 if (disk_activity_last_cycle
) {
900 minutes_disk_activity
++;
901 charge_max_time_now
= charge_max_time_idle
+
902 (minutes_disk_activity
* 2 / 5);
903 disk_activity_last_cycle
= false;
904 last_disk_activity
= 0;
906 last_disk_activity
++;
909 * Check the delta voltage over the last X minutes so we can do
910 * our end-of-charge logic based on the battery level change.
911 *(no longer use minimum time as logic for charge end has 50
912 * minutes minimum charge built in)
914 if (powermgmt_last_cycle_startstop_min
> CHARGE_END_SHORTD
) {
915 short_delta
= power_history
[0] -
916 power_history
[CHARGE_END_SHORTD
- 1];
919 if (powermgmt_last_cycle_startstop_min
> CHARGE_END_LONGD
) {
921 * Scan the history: the points where measurement is taken need to
922 * be fairly static. (check prior to short delta 'area')
923 * (also only check first and last 10 cycles - delta in middle OK)
925 long_delta
= power_history
[0] -
926 power_history
[CHARGE_END_LONGD
- 1];
928 for(i
= CHARGE_END_SHORTD
; i
< CHARGE_END_SHORTD
+ 10; i
++) {
929 if(((power_history
[i
] - power_history
[i
+1]) > 50) ||
930 ((power_history
[i
] - power_history
[i
+1]) < -50)) {
935 for(i
= CHARGE_END_LONGD
- 11; i
< CHARGE_END_LONGD
- 1 ; i
++) {
936 if(((power_history
[i
] - power_history
[i
+1]) > 50) ||
937 ((power_history
[i
] - power_history
[i
+1]) < -50)) {
944 snprintf(power_message
, POWER_MESSAGE_LEN
,
945 "Chg %dm, max %dm", powermgmt_last_cycle_startstop_min
,
946 charge_max_time_now
);
948 * End of charge criteria (any qualify):
949 * 1) Charged a long time
950 * 2) DeltaV went negative for a short time ( & long delta static)
951 * 3) DeltaV was negative over a longer period (no disk use only)
952 * Note: short_delta and long_delta are millivolts
954 if ((powermgmt_last_cycle_startstop_min
>= charge_max_time_now
) ||
955 (short_delta
<= -50 && long_delta
< 50 ) || (long_delta
< -20 &&
956 last_disk_activity
> CHARGE_END_LONGD
)) {
957 if (powermgmt_last_cycle_startstop_min
> charge_max_time_now
) {
958 DEBUGF("power: powermgmt_last_cycle_startstop_min > charge_max_time_now, "
961 *have charged too long and deltaV detection did not
964 snprintf(power_message
, POWER_MESSAGE_LEN
,
965 "Chg tmout %d min", charge_max_time_now
);
967 * Switch to trickle charging. We skip the top-off
968 * since we've effectively done the top-off operation
969 * already since we charged for the maximum full
972 powermgmt_last_cycle_level
= battery_percent
;
973 powermgmt_last_cycle_startstop_min
= 0;
974 charge_state
= TRICKLE
;
977 * set trickle charge target to a relative voltage instead
978 * of an arbitrary value - the fully charged voltage may
979 * vary according to ambient temp, battery condition etc
980 * trickle target is -0.15v from full voltage acheived
981 * topup target is -0.05v from full voltage
983 target_voltage
= power_history
[0] - 150;
986 if(short_delta
<= -5) {
987 DEBUGF("power: short-term negative"
988 " delta, enough!\n");
989 snprintf(power_message
, POWER_MESSAGE_LEN
,
990 "end negd %d %dmin", short_delta
,
991 powermgmt_last_cycle_startstop_min
);
992 target_voltage
= power_history
[CHARGE_END_SHORTD
- 1]
995 DEBUGF("power: long-term small "
996 "positive delta, enough!\n");
997 snprintf(power_message
, POWER_MESSAGE_LEN
,
998 "end lowd %d %dmin", long_delta
,
999 powermgmt_last_cycle_startstop_min
);
1000 target_voltage
= power_history
[CHARGE_END_LONGD
- 1]
1004 * Switch to top-off charging.
1006 powermgmt_last_cycle_level
= battery_percent
;
1007 powermgmt_last_cycle_startstop_min
= 0;
1008 charge_state
= TOPOFF
;
1012 else if (charge_state
!= DISCHARGING
) /* top off or trickle */
1015 *Time to switch from topoff to trickle?
1017 if ((charge_state
== TOPOFF
) &&
1018 (powermgmt_last_cycle_startstop_min
> TOPOFF_MAX_TIME
))
1020 powermgmt_last_cycle_level
= battery_percent
;
1021 powermgmt_last_cycle_startstop_min
= 0;
1022 charge_state
= TRICKLE
;
1023 target_voltage
= target_voltage
- 100;
1026 * Adjust trickle charge time (proportional and integral terms).
1027 * Note: I considered setting the level higher if the USB is
1028 * plugged in, but it doesn't appear to be necessary and will
1029 * generate more heat [gvb].
1032 pid_p
= ((signed)target_voltage
- (signed)battery_millivolts
) / 5;
1033 if((pid_p
<= PID_DEADZONE
) && (pid_p
>= -PID_DEADZONE
))
1036 if((unsigned) battery_millivolts
< target_voltage
) {
1038 pid_i
++; /* limit so it doesn't "wind up" */
1042 pid_i
--; /* limit so it doesn't "wind up" */
1046 trickle_sec
= pid_p
+ pid_i
;
1048 if(trickle_sec
> 60) {
1051 if(trickle_sec
< 0) {
1055 } else if (charge_state
== DISCHARGING
) {
1058 * The charger is enabled here only in one case: if it was
1059 * turned on at boot time (power_init). Turn it off now.
1061 if (charger_enabled
)
1062 charger_enable(false);
1065 if (charger_input_state
== CHARGER_UNPLUGGED
) {
1067 * The charger was just unplugged.
1069 DEBUGF("power: charger disconnected, disabling\n");
1071 charger_enable(false);
1072 powermgmt_last_cycle_level
= battery_percent
;
1073 powermgmt_last_cycle_startstop_min
= 0;
1077 charge_state
= DISCHARGING
;
1078 snprintf(power_message
, POWER_MESSAGE_LEN
, "Charger: discharge");
1081 #endif /* CONFIG_CHARGING == CHARGING_CONTROL */
1083 /* sleep for a minute */
1085 #if CONFIG_CHARGING == CHARGING_CONTROL
1086 if(trickle_sec
> 0) {
1087 charger_enable(true);
1088 power_thread_sleep(HZ
* trickle_sec
);
1090 if(trickle_sec
< 60)
1091 charger_enable(false);
1092 power_thread_sleep(HZ
* (60 - trickle_sec
));
1094 power_thread_sleep(HZ
* 60);
1097 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1098 if(usb_inserted()) {
1100 /* It is probably too late to close the file but we can try...*/
1106 fd
= open(DEBUG_FILE_NAME
, O_WRONLY
| O_APPEND
| O_CREAT
);
1108 snprintf(debug_message
, DEBUG_MESSAGE_LEN
,
1109 "cycle_min, bat_millivolts, bat_percent, chgr_state, charge_state, pid_p, pid_i, trickle_sec\n");
1110 write(fd
, debug_message
, strlen(debug_message
));
1111 wrcount
= 99; /* force a flush */
1115 snprintf(debug_message
, DEBUG_MESSAGE_LEN
,
1116 "%d, %d, %d, %d, %d, %d, %d, %d\n",
1117 powermgmt_last_cycle_startstop_min
, battery_millivolts
,
1118 battery_percent
, charger_input_state
, charge_state
,
1119 pid_p
, pid_i
, trickle_sec
);
1120 write(fd
, debug_message
, strlen(debug_message
));
1125 handle_auto_poweroff();
1127 #if CONFIG_CHARGING == CHARGING_CONTROL
1128 powermgmt_last_cycle_startstop_min
++;
1133 void powermgmt_init(void)
1135 /* init history to 0 */
1136 memset(power_history
, 0x00, sizeof(power_history
));
1137 create_thread(power_thread
, power_stack
, sizeof(power_stack
), 0,
1138 power_thread_name
IF_PRIO(, PRIORITY_SYSTEM
)
1142 #endif /* SIMULATOR */
1144 void sys_poweroff(void)
1146 logf("sys_poweroff()");
1147 /* If the main thread fails to shut down the system, we will force a
1148 power off after an 20 second timeout - 28 seconds if recording */
1149 if (shutdown_timeout
== 0)
1151 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1152 pcf50606_reset_timeout(); /* Reset timer on first attempt only */
1154 #ifdef HAVE_RECORDING
1155 if (audio_status() & AUDIO_STATUS_RECORD
)
1156 shutdown_timeout
+= HZ
*8;
1158 shutdown_timeout
+= HZ
*20;
1161 queue_broadcast(SYS_POWEROFF
, 0);
1164 void cancel_shutdown(void)
1166 logf("sys_cancel_shutdown()");
1168 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1169 /* TODO: Move some things to target/ tree */
1170 if (shutdown_timeout
)
1171 pcf50606_reset_timeout();
1174 shutdown_timeout
= 0;
1177 /* Various hardware housekeeping tasks relating to shutting down the jukebox */
1178 void shutdown_hw(void)
1181 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1188 if (battery_level_safe()) { /* do not save on critical battery */
1189 #ifdef HAVE_LCD_BITMAP
1192 if(ata_disk_is_active())
1195 while(ata_disk_is_active())
1198 #if CONFIG_CODEC != SWCODEC
1204 /* If HD is still active we try to wait for spindown, otherwise the
1205 shutdown_timeout in power_thread_sleep will force a power off */
1206 while(ata_disk_is_active())
1209 lcd_set_contrast(0);
1210 #endif /* IAUDIO_X5 */
1211 #ifdef HAVE_REMOTE_LCD
1212 lcd_remote_set_contrast(0);
1215 #ifdef HAVE_LCD_SHUTDOWN
1219 /* Small delay to make sure all HW gets time to flush. Especially
1220 eeprom chips are quite slow and might be still writing the last
1224 #endif /* #ifndef SIMULATOR */
1227 /* Send system battery level update events on reaching certain significant
1228 levels. This must be called after battery_percent has been updated. */
1229 static void send_battery_level_event(void)
1231 static const int levels
[] = { 5, 15, 30, 50, 0 };
1232 const int *level
= levels
;
1235 if (battery_percent
<= *level
&& last_sent_battery_level
> *level
)
1237 last_sent_battery_level
= *level
;
1238 queue_broadcast(SYS_BATTERY_UPDATE
, last_sent_battery_level
);