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 * This program is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU General Public License
15 * as published by the Free Software Foundation; either version 2
16 * of the License, or (at your option) any later version.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ****************************************************************************/
32 #include "mp3_playback.h"
34 #include "powermgmt.h"
35 #include "backlight.h"
42 #ifdef HAVE_LCD_BITMAP
46 #include "lcd-remote.h"
47 #if (CONFIG_PLATFORM & PLATFORM_HOSTED)
54 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
55 #include "lcd-remote-target.h"
57 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5) || defined(COWON_D2)) \
58 && !defined (SIMULATOR)
63 int last_sent_battery_level
= 100;
64 /* battery level (0-100%) */
65 int battery_percent
= -1;
66 void send_battery_level_event(void);
68 static bool sleeptimer_active
= false;
69 static long sleeptimer_endtick
;
72 /* State of the charger input as seen by the power thread */
73 enum charger_input_state_type charger_input_state
;
74 /* Power inputs as seen by the power thread */
75 unsigned int power_thread_inputs
;
76 #if CONFIG_CHARGING >= CHARGING_MONITOR
77 /* Charging state (mode) as seen by the power thread */
78 enum charge_state_type charge_state
= DISCHARGING
;
80 #endif /* CONFIG_CHARGING */
82 static int shutdown_timeout
= 0;
84 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
86 * Average battery voltage and charger voltage, filtered via a digital
87 * exponential filter (aka. exponential moving average, scaled):
88 * avgbat = y[n] = (N-1)/N*y[n-1] + x[n]. battery_millivolts = y[n] / N.
90 static unsigned int avgbat
;
91 /* filtered battery voltage, millivolts */
92 static unsigned int battery_millivolts
;
93 /* default value, mAh */
94 static int battery_capacity
= BATTERY_CAPACITY_DEFAULT
;
97 #if BATTERY_TYPES_COUNT > 1
98 static int battery_type
= 0;
100 #define battery_type 0
103 /* Power history: power_history[0] is the newest sample */
104 unsigned short power_history
[POWER_HISTORY_LEN
] = {0};
106 #if CONFIG_CPU == JZ4732 /* FIXME! */
107 static char power_stack
[DEFAULT_STACK_SIZE
+ POWERMGMT_DEBUG_STACK
];
109 static char power_stack
[DEFAULT_STACK_SIZE
/2 + POWERMGMT_DEBUG_STACK
];
111 static const char power_thread_name
[] = "power";
113 static int poweroff_timeout
= 0;
114 static int powermgmt_est_runningtime_min
= -1;
116 static long last_event_tick
;
118 static int voltage_to_battery_level(int battery_millivolts
);
119 static void battery_status_update(void);
121 #ifdef CURRENT_NORMAL /*only used if we have run current*/
122 static int runcurrent(void);
125 void battery_read_info(int *voltage
, int *level
)
127 int millivolts
= battery_adc_voltage();
130 *voltage
= millivolts
;
133 *level
= voltage_to_battery_level(millivolts
);
136 void reset_poweroff_timer(void)
138 last_event_tick
= current_tick
;
141 #if BATTERY_TYPES_COUNT > 1
142 void set_battery_type(int type
)
144 if (type
!= battery_type
) {
145 if ((unsigned)type
>= BATTERY_TYPES_COUNT
)
149 battery_status_update(); /* recalculate the battery status */
154 void set_battery_capacity(int capacity
)
156 if (capacity
> BATTERY_CAPACITY_MAX
)
157 capacity
= BATTERY_CAPACITY_MAX
;
158 if (capacity
< BATTERY_CAPACITY_MIN
)
159 capacity
= BATTERY_CAPACITY_MIN
;
161 battery_capacity
= capacity
;
163 battery_status_update(); /* recalculate the battery status */
166 int get_battery_capacity(void)
168 return battery_capacity
;
171 int battery_time(void)
173 return powermgmt_est_runningtime_min
;
176 /* Returns battery level in percent */
177 int battery_level(void)
179 #ifdef HAVE_BATTERY_SWITCH
180 if ((power_input_status() & POWER_INPUT_BATTERY
) == 0)
183 return battery_percent
;
186 /* Returns filtered battery voltage [millivolts] */
187 unsigned int battery_voltage(void)
189 return battery_millivolts
;
192 /* Tells if the battery level is safe for disk writes */
193 bool battery_level_safe(void)
195 #if defined(NO_LOW_BATTERY_SHUTDOWN)
197 #elif defined(HAVE_BATTERY_SWITCH)
198 /* Cannot rely upon the battery reading to be valid and the
199 * device could be powered externally. */
200 return input_millivolts() > battery_level_dangerous
[battery_type
];
202 return battery_millivolts
> battery_level_dangerous
[battery_type
];
206 void set_poweroff_timeout(int timeout
)
208 poweroff_timeout
= timeout
;
211 /* look into the percent_to_volt_* table and get a realistic battery level */
212 static int voltage_to_percent(int voltage
, const short* table
)
214 if (voltage
<= table
[0]) {
217 else if (voltage
>= table
[10]) {
221 /* search nearest value */
224 while (i
< 10 && table
[i
+1] < voltage
)
227 /* interpolate linear between the smaller and greater value */
228 /* Tens digit, 10% per entry, ones digit: interpolated */
229 return i
*10 + (voltage
- table
[i
])*10 / (table
[i
+1] - table
[i
]);
233 /* update battery level and estimated runtime, called once per minute or
234 * when battery capacity / type settings are changed */
235 static int voltage_to_battery_level(int battery_millivolts
)
239 #if CONFIG_CHARGING >= CHARGING_MONITOR
240 if (charging_state()) {
241 /* battery level is defined to be < 100% until charging is finished */
242 level
= voltage_to_percent(battery_millivolts
,
243 percent_to_volt_charge
);
248 #endif /* CONFIG_CHARGING >= CHARGING_MONITOR */
250 /* DISCHARGING or error state */
251 level
= voltage_to_percent(battery_millivolts
,
252 percent_to_volt_discharge
[battery_type
]);
258 static void battery_status_update(void)
260 int level
= voltage_to_battery_level(battery_millivolts
);
262 #ifdef CURRENT_NORMAL /*don't try to estimate run or charge
263 time without normal current defined*/
264 /* calculate estimated remaining running time */
265 #if CONFIG_CHARGING >= CHARGING_MONITOR
266 if (charging_state()) {
267 /* charging: remaining charging time */
268 powermgmt_est_runningtime_min
= (100 - level
)*battery_capacity
*60
269 / 100 / (CURRENT_MAX_CHG
- runcurrent());
274 /* discharging: remaining running time */
275 if (battery_millivolts
> percent_to_volt_discharge
[0][0]) {
276 /* linear extrapolation */
277 powermgmt_est_runningtime_min
= (level
+ battery_percent
)*60
278 * battery_capacity
/ 200 / runcurrent();
280 if (0 > powermgmt_est_runningtime_min
) {
281 powermgmt_est_runningtime_min
= 0;
284 powermgmt_est_runningtime_min
=-1;
287 battery_percent
= level
;
288 send_battery_level_event();
292 * We shut off in the following cases:
293 * 1) The unit is idle, not playing music
294 * 2) The unit is playing music, but is paused
295 * 3) The battery level has reached shutdown limit
297 * We do not shut off in the following cases:
298 * 1) The USB is connected
299 * 2) The charger is connected
300 * 3) We are recording, or recording with pause
301 * 4) The radio is playing
303 static void handle_auto_poweroff(void)
305 long timeout
= poweroff_timeout
*60*HZ
;
306 int audio_stat
= audio_status();
307 long tick
= current_tick
;
311 * Inhibit shutdown as long as the charger is plugged in. If it is
312 * unplugged, wait for a timeout period and then shut down.
314 if (charger_input_state
== CHARGER
|| audio_stat
== AUDIO_STATUS_PLAY
) {
315 last_event_tick
= current_tick
;
319 if (!shutdown_timeout
&& query_force_shutdown()) {
326 !(get_radio_status() & FMRADIO_PLAYING
) &&
330 (audio_stat
== (AUDIO_STATUS_PLAY
| AUDIO_STATUS_PAUSE
) &&
331 !sleeptimer_active
))) {
333 if (TIME_AFTER(tick
, last_event_tick
+ timeout
) &&
334 TIME_AFTER(tick
, storage_last_disk_activity() + timeout
)) {
338 handle_sleep_timer();
341 #ifdef CURRENT_NORMAL /*check that we have a current defined in a config file*/
344 * Estimate how much current we are drawing just to run.
346 static int runcurrent(void)
348 int current
= CURRENT_NORMAL
;
352 #ifdef HAVE_USB_POWER
353 #if (CURRENT_USB < CURRENT_NORMAL)
360 current
= CURRENT_USB
;
363 #if defined(HAVE_BACKLIGHT)
364 if (backlight_get_current_timeout() == 0) /* LED always on */
365 current
+= CURRENT_BACKLIGHT
;
368 #if defined(HAVE_RECORDING) && defined(CURRENT_RECORD)
369 if (audio_status() & AUDIO_STATUS_RECORD
)
370 current
+= CURRENT_RECORD
;
373 #ifdef HAVE_SPDIF_POWER
375 current
+= CURRENT_SPDIF_OUT
;
378 #ifdef HAVE_REMOTE_LCD
380 current
+= CURRENT_REMOTE
;
383 #if defined(HAVE_ATA_POWER_OFF) && defined(CURRENT_ATA)
385 current
+= CURRENT_ATA
;
388 #endif /* BOOTLOADER */
393 #endif /* CURRENT_NORMAL */
395 /* Check to see whether or not we've received an alarm in the last second */
396 #ifdef HAVE_RTC_ALARM
397 static void power_thread_rtc_process(void)
399 if (rtc_check_alarm_flag())
400 rtc_enable_alarm(false);
404 /* switch off unit if battery level is too low for reliable operation */
405 bool query_force_shutdown(void)
407 #if defined(NO_LOW_BATTERY_SHUTDOWN)
409 #elif defined(HAVE_BATTERY_SWITCH)
410 /* Cannot rely upon the battery reading to be valid and the
411 * device could be powered externally. */
412 return input_millivolts() < battery_level_shutoff
[battery_type
];
414 return battery_millivolts
< battery_level_shutoff
[battery_type
];
418 #if defined(HAVE_BATTERY_SWITCH) || defined(HAVE_RESET_BATTERY_FILTER)
420 * Reset the battery voltage filter to a new value and update the
423 void reset_battery_filter(int millivolts
)
425 avgbat
= millivolts
* BATT_AVE_SAMPLES
;
426 battery_millivolts
= millivolts
;
427 battery_status_update();
429 #endif /* HAVE_BATTERY_SWITCH */
431 /** Generic charging algorithms for common charging types **/
432 #if CONFIG_CHARGING == 0 || CONFIG_CHARGING == CHARGING_SIMPLE
433 static inline void powermgmt_init_target(void)
438 static inline void charging_algorithm_step(void)
443 static inline void charging_algorithm_close(void)
447 #elif CONFIG_CHARGING == CHARGING_MONITOR
449 * Monitor CHARGING/DISCHARGING state.
451 static inline void powermgmt_init_target(void)
456 static inline void charging_algorithm_step(void)
458 switch (charger_input_state
)
460 case CHARGER_PLUGGED
:
462 if (charging_state()) {
463 charge_state
= CHARGING
;
467 case CHARGER_UNPLUGGED
:
469 charge_state
= DISCHARGING
;
474 static inline void charging_algorithm_close(void)
478 #endif /* CONFIG_CHARGING == * */
481 /* Shortcut function calls - compatibility, simplicity. */
483 /* Returns true if any power input is capable of charging. */
484 bool charger_inserted(void)
486 return power_thread_inputs
& POWER_INPUT_CHARGER
;
489 /* Returns true if any power input is connected - charging-capable
491 bool power_input_present(void)
493 return power_thread_inputs
& POWER_INPUT
;
497 * Detect charger inserted. Return true if the state is transistional.
499 static inline bool detect_charger(unsigned int pwr
)
502 * Detect charger plugged/unplugged transitions. On a plugged or
503 * unplugged event, we return immediately, run once through the main
504 * loop (including the subroutines), and end up back here where we
505 * transition to the appropriate steady state charger on/off state.
507 if (pwr
& POWER_INPUT_CHARGER
) {
508 switch (charger_input_state
)
511 case CHARGER_UNPLUGGED
:
512 charger_input_state
= CHARGER_PLUGGED
;
515 case CHARGER_PLUGGED
:
516 queue_broadcast(SYS_CHARGER_CONNECTED
, 0);
517 last_sent_battery_level
= 0;
518 charger_input_state
= CHARGER
;
526 else { /* charger not inserted */
527 switch (charger_input_state
)
533 case CHARGER_UNPLUGGED
:
534 queue_broadcast(SYS_CHARGER_DISCONNECTED
, 0);
535 last_sent_battery_level
= 100;
536 charger_input_state
= NO_CHARGER
;
539 case CHARGER_PLUGGED
:
541 charger_input_state
= CHARGER_UNPLUGGED
;
546 /* Transitional state */
549 #endif /* CONFIG_CHARGING */
552 * Monitor the presence of a charger and perform critical frequent steps
553 * such as running the battery voltage filter.
555 static inline void power_thread_step(void)
557 /* If the power off timeout expires, the main thread has failed
558 to shut down the system, and we need to force a power off */
559 if (shutdown_timeout
) {
560 shutdown_timeout
-= POWER_THREAD_STEP_TICKS
;
562 if (shutdown_timeout
<= 0)
566 #ifdef HAVE_RTC_ALARM
567 power_thread_rtc_process();
571 * Do a digital exponential filter. We don't sample the battery if
572 * the disk is spinning unless we are in USB mode (the disk will most
573 * likely always be spinning in USB mode) or charging.
575 if (!storage_disk_is_active() || usb_inserted()
576 #if CONFIG_CHARGING >= CHARGING_MONITOR
577 || charger_input_state
== CHARGER
580 avgbat
+= battery_adc_voltage() - avgbat
/ BATT_AVE_SAMPLES
;
582 * battery_millivolts is the millivolt-scaled filtered battery value.
584 battery_millivolts
= avgbat
/ BATT_AVE_SAMPLES
;
586 /* update battery status every time an update is available */
587 battery_status_update();
589 else if (battery_percent
< 8) {
591 * If battery is low, observe voltage during disk activity.
592 * Shut down if voltage drops below shutoff level and we are not
593 * using NiMH or Alkaline batteries.
595 battery_millivolts
= (battery_adc_voltage() +
596 battery_millivolts
+ 1) / 2;
598 /* update battery status every time an update is available */
599 battery_status_update();
601 if (!shutdown_timeout
&& query_force_shutdown()) {
605 avgbat
+= battery_millivolts
- avgbat
/ BATT_AVE_SAMPLES
;
608 } /* power_thread_step */
610 static void power_thread(void)
612 long next_power_hist
;
614 /* Delay reading the first battery level */
616 while (battery_adc_voltage() > 4200) /* gives false readings initially */
623 /* Initialize power input status before calling other routines. */
624 power_thread_inputs
= power_input_status();
627 /* initialize the voltages for the exponential filter */
628 avgbat
= battery_adc_voltage() + 15;
630 #ifdef HAVE_DISK_STORAGE /* this adjustment is only needed for HD based */
631 /* The battery voltage is usually a little lower directly after
632 turning on, because the disk was used heavily. Raise it by 5% */
634 if (!charger_inserted()) /* only if charger not connected */
637 avgbat
+= (percent_to_volt_discharge
[battery_type
][6] -
638 percent_to_volt_discharge
[battery_type
][5]) / 2;
640 #endif /* HAVE_DISK_STORAGE */
642 avgbat
= avgbat
* BATT_AVE_SAMPLES
;
643 battery_millivolts
= avgbat
/ BATT_AVE_SAMPLES
;
644 power_history
[0] = battery_millivolts
;
647 if (charger_inserted()) {
648 battery_percent
= voltage_to_percent(battery_millivolts
,
649 percent_to_volt_charge
);
654 battery_percent
= voltage_to_percent(battery_millivolts
,
655 percent_to_volt_discharge
[battery_type
]);
656 battery_percent
+= battery_percent
< 100;
659 powermgmt_init_target();
661 next_power_hist
= current_tick
+ HZ
*60;
666 unsigned int pwr
= power_input_status();
667 #ifdef HAVE_BATTERY_SWITCH
668 if ((pwr
^ power_thread_inputs
) & POWER_INPUT_BATTERY
) {
670 reset_battery_filter(battery_adc_voltage());
673 power_thread_inputs
= pwr
;
675 if (!detect_charger(pwr
))
676 #endif /* CONFIG_CHARGING */
679 sleep(POWER_THREAD_STEP_TICKS
);
681 /* Do common power tasks */
685 /* Perform target tasks */
686 charging_algorithm_step();
688 if (TIME_BEFORE(current_tick
, next_power_hist
))
691 /* increment to ensure there is a record for every minute
692 * rather than go forward from the current tick */
693 next_power_hist
+= HZ
*60;
695 /* rotate the power history */
696 memmove(&power_history
[1], &power_history
[0],
697 sizeof(power_history
) - sizeof(power_history
[0]));
699 /* insert new value at the start, in millivolts 8-) */
700 power_history
[0] = battery_millivolts
;
702 handle_auto_poweroff();
706 void powermgmt_init(void)
708 create_thread(power_thread
, power_stack
, sizeof(power_stack
), 0,
709 power_thread_name
IF_PRIO(, PRIORITY_SYSTEM
)
713 /* Various hardware housekeeping tasks relating to shutting down the player */
714 void shutdown_hw(void)
716 charging_algorithm_close();
719 if (battery_level_safe()) { /* do not save on critical battery */
720 #ifdef HAVE_LCD_BITMAP
721 glyph_cache_save(NULL
);
724 /* Commit pending writes if needed. Even though we don't do write caching,
725 things like flash translation layers may need this to commit scattered
726 pages to there final locations. So far only used for iPod Nano 2G. */
727 #ifdef HAVE_STORAGE_FLUSH
731 if (storage_disk_is_active())
735 #if CONFIG_CODEC == SWCODEC
741 /* If HD is still active we try to wait for spindown, otherwise the
742 shutdown_timeout in power_thread_step will force a power off */
743 while (storage_disk_is_active())
746 #ifndef HAVE_LCD_COLOR
749 #ifdef HAVE_REMOTE_LCD
750 lcd_remote_set_contrast(0);
752 #ifdef HAVE_LCD_SHUTDOWN
756 /* Small delay to make sure all HW gets time to flush. Especially
757 eeprom chips are quite slow and might be still writing the last
762 #endif /* PLATFORM_NATIVE */
764 void sys_poweroff(void)
767 logf("sys_poweroff()");
768 /* If the main thread fails to shut down the system, we will force a
769 power off after an 20 second timeout - 28 seconds if recording */
770 if (shutdown_timeout
== 0) {
771 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5) || defined(COWON_D2)) && !defined(SIMULATOR)
772 pcf50606_reset_timeout(); /* Reset timer on first attempt only */
774 #ifdef HAVE_RECORDING
775 if (audio_status() & AUDIO_STATUS_RECORD
)
776 shutdown_timeout
+= HZ
*8;
779 /* The FTL alone may take half a minute to shut down cleanly. */
780 shutdown_timeout
+= HZ
*60;
782 shutdown_timeout
+= HZ
*20;
786 queue_broadcast(SYS_POWEROFF
, 0);
787 #endif /* BOOTLOADER */
790 void cancel_shutdown(void)
792 logf("cancel_shutdown()");
794 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5) || defined(COWON_D2)) && !defined(SIMULATOR)
795 /* TODO: Move some things to target/ tree */
796 if (shutdown_timeout
)
797 pcf50606_reset_timeout();
800 shutdown_timeout
= 0;
803 /* Send system battery level update events on reaching certain significant
804 levels. This must be called after battery_percent has been updated. */
805 void send_battery_level_event(void)
807 static const int levels
[] = { 5, 15, 30, 50, 0 };
808 const int *level
= levels
;
812 if (battery_percent
<= *level
&& last_sent_battery_level
> *level
) {
813 last_sent_battery_level
= *level
;
814 queue_broadcast(SYS_BATTERY_UPDATE
, last_sent_battery_level
);
822 void set_sleep_timer(int seconds
)
825 sleeptimer_active
= true;
826 sleeptimer_endtick
= current_tick
+ seconds
* HZ
;
829 sleeptimer_active
= false;
830 sleeptimer_endtick
= 0;
834 int get_sleep_timer(void)
836 if (sleeptimer_active
&& (sleeptimer_endtick
>= current_tick
))
837 return (sleeptimer_endtick
- current_tick
) / HZ
;
842 void handle_sleep_timer(void)
844 if (!sleeptimer_active
)
847 /* Handle sleeptimer */
848 if (TIME_AFTER(current_tick
, sleeptimer_endtick
)) {
850 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
851 || charger_input_state
!= NO_CHARGER
854 DEBUGF("Sleep timer timeout. Stopping...\n");
856 bookmark_autobookmark(false);
860 backlight_off(); /* Nighty, nighty... */
863 DEBUGF("Sleep timer timeout. Shutting off...\n");