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"
51 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
53 #include "lcd-remote-target.h"
57 int last_sent_battery_level
= 100;
58 /* battery level (0-100%) */
59 int battery_percent
= -1;
60 void send_battery_level_event(void);
63 /* State of the charger input as seen by the power thread */
64 enum charger_input_state_type charger_input_state
;
65 /* Power inputs as seen by the power thread */
66 unsigned int power_thread_inputs
;
67 #if CONFIG_CHARGING >= CHARGING_MONITOR
68 /* Charging state (mode) as seen by the power thread */
69 enum charge_state_type charge_state
= DISCHARGING
;
71 #endif /* CONFIG_CHARGING */
74 static int shutdown_timeout
= 0;
76 * Average battery voltage and charger voltage, filtered via a digital
77 * exponential filter (aka. exponential moving average, scaled):
78 * avgbat = y[n] = (N-1)/N*y[n-1] + x[n]. battery_millivolts = y[n] / N.
80 static unsigned int avgbat
;
81 /* filtered battery voltage, millivolts */
82 static unsigned int battery_millivolts
;
83 /* default value, mAh */
84 static int battery_capacity
= BATTERY_CAPACITY_DEFAULT
;
87 #if BATTERY_TYPES_COUNT > 1
88 static int battery_type
= 0;
90 #define battery_type 0
93 /* Power history: power_history[0] is the newest sample */
94 unsigned short power_history
[POWER_HISTORY_LEN
];
96 static char power_stack
[DEFAULT_STACK_SIZE
/2 + POWERMGMT_DEBUG_STACK
];
97 static const char power_thread_name
[] = "power";
99 static int poweroff_timeout
= 0;
100 static int powermgmt_est_runningtime_min
= -1;
102 static bool sleeptimer_active
= false;
103 static long sleeptimer_endtick
;
105 static long last_event_tick
;
107 static int voltage_to_battery_level(int battery_millivolts
);
108 static void battery_status_update(void);
109 static int runcurrent(void);
111 void battery_read_info(int *voltage
, int *level
)
113 int millivolts
= battery_adc_voltage();
116 *voltage
= millivolts
;
119 *level
= voltage_to_battery_level(millivolts
);
122 void reset_poweroff_timer(void)
124 last_event_tick
= current_tick
;
127 #if BATTERY_TYPES_COUNT > 1
128 void set_battery_type(int type
)
130 if (type
!= battery_type
) {
131 if ((unsigned)type
>= BATTERY_TYPES_COUNT
)
135 battery_status_update(); /* recalculate the battery status */
140 void set_battery_capacity(int capacity
)
142 if (capacity
> BATTERY_CAPACITY_MAX
)
143 capacity
= BATTERY_CAPACITY_MAX
;
144 if (capacity
< BATTERY_CAPACITY_MIN
)
145 capacity
= BATTERY_CAPACITY_MIN
;
147 battery_capacity
= capacity
;
149 battery_status_update(); /* recalculate the battery status */
152 int get_battery_capacity(void)
154 return battery_capacity
;
157 int battery_time(void)
159 return powermgmt_est_runningtime_min
;
162 /* Returns battery level in percent */
163 int battery_level(void)
165 #ifdef HAVE_BATTERY_SWITCH
166 if ((power_input_status() & POWER_INPUT_BATTERY
) == 0)
169 return battery_percent
;
172 /* Returns filtered battery voltage [millivolts] */
173 unsigned int battery_voltage(void)
175 return battery_millivolts
;
178 /* Tells if the battery level is safe for disk writes */
179 bool battery_level_safe(void)
181 #if defined(NO_LOW_BATTERY_SHUTDOWN)
183 #elif defined(HAVE_BATTERY_SWITCH)
184 /* Cannot rely upon the battery reading to be valid and the
185 * device could be powered externally. */
186 return input_millivolts() > battery_level_dangerous
[battery_type
];
188 return battery_millivolts
> battery_level_dangerous
[battery_type
];
192 void set_poweroff_timeout(int timeout
)
194 poweroff_timeout
= timeout
;
197 void set_sleep_timer(int seconds
)
200 sleeptimer_active
= true;
201 sleeptimer_endtick
= current_tick
+ seconds
* HZ
;
204 sleeptimer_active
= false;
205 sleeptimer_endtick
= 0;
209 int get_sleep_timer(void)
211 if (sleeptimer_active
)
212 return (sleeptimer_endtick
- current_tick
) / HZ
;
217 /* look into the percent_to_volt_* table and get a realistic battery level */
218 static int voltage_to_percent(int voltage
, const short* table
)
220 if (voltage
<= table
[0]) {
223 else if (voltage
>= table
[10]) {
227 /* search nearest value */
230 while (i
< 10 && table
[i
+1] < voltage
)
233 /* interpolate linear between the smaller and greater value */
234 /* Tens digit, 10% per entry, ones digit: interpolated */
235 return i
*10 + (voltage
- table
[i
])*10 / (table
[i
+1] - table
[i
]);
239 /* update battery level and estimated runtime, called once per minute or
240 * when battery capacity / type settings are changed */
241 static int voltage_to_battery_level(int battery_millivolts
)
245 #if CONFIG_CHARGING >= CHARGING_MONITOR
246 if (charging_state()) {
247 /* battery level is defined to be < 100% until charging is finished */
248 level
= voltage_to_percent(battery_millivolts
,
249 percent_to_volt_charge
);
254 #endif /* CONFIG_CHARGING >= CHARGING_MONITOR */
256 /* DISCHARGING or error state */
257 level
= voltage_to_percent(battery_millivolts
,
258 percent_to_volt_discharge
[battery_type
]);
264 static void battery_status_update(void)
266 int level
= voltage_to_battery_level(battery_millivolts
);
268 /* calculate estimated remaining running time */
269 #if CONFIG_CHARGING >= CHARGING_MONITOR
270 if (charging_state()) {
271 /* charging: remaining charging time */
272 powermgmt_est_runningtime_min
= (100 - level
)*battery_capacity
*60
273 / 100 / (CURRENT_MAX_CHG
- runcurrent());
277 /* discharging: remaining running time */
278 if ((battery_millivolts
+ 20) > percent_to_volt_discharge
[0][0]) {
279 powermgmt_est_runningtime_min
= (level
+ battery_percent
)*60
280 * battery_capacity
/ 200 / runcurrent();
282 else if (battery_millivolts
<= battery_level_shutoff
[0]) {
283 powermgmt_est_runningtime_min
= 0;
286 powermgmt_est_runningtime_min
=
287 (battery_millivolts
- battery_level_shutoff
[0]) / 2;
290 battery_percent
= level
;
291 send_battery_level_event();
295 * We shut off in the following cases:
296 * 1) The unit is idle, not playing music
297 * 2) The unit is playing music, but is paused
298 * 3) The battery level has reached shutdown limit
300 * We do not shut off in the following cases:
301 * 1) The USB is connected
302 * 2) The charger is connected
303 * 3) We are recording, or recording with pause
304 * 4) The radio is playing
306 static void handle_auto_poweroff(void)
308 long timeout
= poweroff_timeout
*60*HZ
;
309 int audio_stat
= audio_status();
310 long tick
= current_tick
;
314 * Inhibit shutdown as long as the charger is plugged in. If it is
315 * unplugged, wait for a timeout period and then shut down.
317 if (charger_input_state
== CHARGER
|| audio_stat
== AUDIO_STATUS_PLAY
) {
318 last_event_tick
= current_tick
;
322 if (!shutdown_timeout
&& query_force_shutdown()) {
329 !(get_radio_status() & FMRADIO_PLAYING
) &&
333 (audio_stat
== (AUDIO_STATUS_PLAY
| AUDIO_STATUS_PAUSE
) &&
334 !sleeptimer_active
))) {
336 if (TIME_AFTER(tick
, last_event_tick
+ timeout
) &&
337 TIME_AFTER(tick
, storage_last_disk_activity() + timeout
)) {
341 else if (sleeptimer_active
) {
342 /* Handle sleeptimer */
343 if (TIME_AFTER(tick
, sleeptimer_endtick
)) {
347 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
348 || charger_input_state
!= NO_CHARGER
351 DEBUGF("Sleep timer timeout. Stopping...\n");
353 backlight_off(); /* Nighty, nighty... */
356 DEBUGF("Sleep timer timeout. Shutting off...\n");
364 * Estimate how much current we are drawing just to run.
366 static int runcurrent(void)
370 #if MEM == 8 && !(defined(ARCHOS_ONDIOSP) || defined(ARCHOS_ONDIOFM))
371 /* assuming 192 kbps, the running time is 22% longer with 8MB */
372 current
= CURRENT_NORMAL
*100 / 122;
374 current
= CURRENT_NORMAL
;
375 #endif /* MEM == 8 */
379 #ifdef HAVE_USB_POWER
380 #if (CURRENT_USB < CURRENT_NORMAL)
387 current
= CURRENT_USB
;
390 #if defined(HAVE_BACKLIGHT)
391 if (backlight_get_current_timeout() == 0) /* LED always on */
392 current
+= CURRENT_BACKLIGHT
;
395 #if defined(HAVE_RECORDING) && defined(CURRENT_RECORD)
396 if (audio_status() & AUDIO_STATUS_RECORD
)
397 current
+= CURRENT_RECORD
;
400 #ifdef HAVE_SPDIF_POWER
402 current
+= CURRENT_SPDIF_OUT
;
405 #ifdef HAVE_REMOTE_LCD
407 current
+= CURRENT_REMOTE
;
409 #endif /* BOOTLOADER */
415 /* Check to see whether or not we've received an alarm in the last second */
416 #ifdef HAVE_RTC_ALARM
417 static void power_thread_rtc_process(void)
419 if (rtc_check_alarm_flag())
420 rtc_enable_alarm(false);
424 /* switch off unit if battery level is too low for reliable operation */
425 bool query_force_shutdown(void)
427 #if defined(NO_LOW_BATTERY_SHUTDOWN)
429 #elif defined(HAVE_BATTERY_SWITCH)
430 /* Cannot rely upon the battery reading to be valid and the
431 * device could be powered externally. */
432 return input_millivolts() < battery_level_shutoff
[battery_type
];
434 return battery_millivolts
< battery_level_shutoff
[battery_type
];
438 #if defined(HAVE_BATTERY_SWITCH) || defined(HAVE_RESET_BATTERY_FILTER)
440 * Reset the battery voltage filter to a new value and update the
443 void reset_battery_filter(int millivolts
)
445 avgbat
= millivolts
* BATT_AVE_SAMPLES
;
446 battery_millivolts
= millivolts
;
447 battery_status_update();
449 #endif /* HAVE_BATTERY_SWITCH */
451 /** Generic charging algorithms for common charging types **/
452 #if CONFIG_CHARGING == 0 || CONFIG_CHARGING == CHARGING_SIMPLE
453 static inline void powermgmt_init_target(void)
458 static inline void charging_algorithm_step(void)
463 static inline void charging_algorithm_close(void)
467 #elif CONFIG_CHARGING == CHARGING_MONITOR
469 * Monitor CHARGING/DISCHARGING state.
471 static inline void powermgmt_init_target(void)
476 static inline void charging_algorithm_step(void)
478 switch (charger_input_state
)
480 case CHARGER_PLUGGED
:
482 if (charging_state()) {
483 charge_state
= CHARGING
;
487 case CHARGER_UNPLUGGED
:
489 charge_state
= DISCHARGING
;
494 static inline void charging_algorithm_close(void)
498 #endif /* CONFIG_CHARGING == * */
501 /* Shortcut function calls - compatibility, simplicity. */
503 /* Returns true if any power input is capable of charging. */
504 bool charger_inserted(void)
506 return power_thread_inputs
& POWER_INPUT_CHARGER
;
509 /* Returns true if any power input is connected - charging-capable
511 bool power_input_present(void)
513 return power_thread_inputs
& POWER_INPUT
;
517 * Detect charger inserted. Return true if the state is transistional.
519 static inline bool detect_charger(unsigned int pwr
)
522 * Detect charger plugged/unplugged transitions. On a plugged or
523 * unplugged event, we return immediately, run once through the main
524 * loop (including the subroutines), and end up back here where we
525 * transition to the appropriate steady state charger on/off state.
527 if (pwr
& POWER_INPUT_CHARGER
) {
528 switch (charger_input_state
)
531 case CHARGER_UNPLUGGED
:
532 charger_input_state
= CHARGER_PLUGGED
;
535 case CHARGER_PLUGGED
:
536 queue_broadcast(SYS_CHARGER_CONNECTED
, 0);
537 last_sent_battery_level
= 0;
538 charger_input_state
= CHARGER
;
546 else { /* charger not inserted */
547 switch (charger_input_state
)
553 case CHARGER_UNPLUGGED
:
554 queue_broadcast(SYS_CHARGER_DISCONNECTED
, 0);
555 last_sent_battery_level
= 100;
556 charger_input_state
= NO_CHARGER
;
559 case CHARGER_PLUGGED
:
561 charger_input_state
= CHARGER_UNPLUGGED
;
566 /* Transitional state */
569 #endif /* CONFIG_CHARGING */
572 * Monitor the presence of a charger and perform critical frequent steps
573 * such as running the battery voltage filter.
575 static inline void power_thread_step(void)
577 /* If the power off timeout expires, the main thread has failed
578 to shut down the system, and we need to force a power off */
579 if (shutdown_timeout
) {
580 shutdown_timeout
-= POWER_THREAD_STEP_TICKS
;
582 if (shutdown_timeout
<= 0)
586 #ifdef HAVE_RTC_ALARM
587 power_thread_rtc_process();
591 * Do a digital exponential filter. We don't sample the battery if
592 * the disk is spinning unless we are in USB mode (the disk will most
593 * likely always be spinning in USB mode) or charging.
595 if (!storage_disk_is_active() || usb_inserted()
596 #if CONFIG_CHARGING >= CHARGING_MONITOR
597 || charger_input_state
== CHARGER
600 avgbat
+= battery_adc_voltage() - avgbat
/ BATT_AVE_SAMPLES
;
602 * battery_millivolts is the millivolt-scaled filtered battery value.
604 battery_millivolts
= avgbat
/ BATT_AVE_SAMPLES
;
606 /* update battery status every time an update is available */
607 battery_status_update();
609 else if (battery_percent
< 8) {
611 * If battery is low, observe voltage during disk activity.
612 * Shut down if voltage drops below shutoff level and we are not
613 * using NiMH or Alkaline batteries.
615 battery_millivolts
= (battery_adc_voltage() +
616 battery_millivolts
+ 1) / 2;
618 /* update battery status every time an update is available */
619 battery_status_update();
621 if (!shutdown_timeout
&& query_force_shutdown()) {
625 avgbat
+= battery_millivolts
- avgbat
/ BATT_AVE_SAMPLES
;
628 } /* power_thread_step */
630 static void power_thread(void)
632 long next_power_hist
;
634 /* Delay reading the first battery level */
636 while (battery_adc_voltage() > 4200) /* gives false readings initially */
643 /* Initialize power input status before calling other routines. */
644 power_thread_inputs
= power_input_status();
647 /* initialize the voltages for the exponential filter */
648 avgbat
= battery_adc_voltage() + 15;
650 #ifdef HAVE_DISK_STORAGE /* this adjustment is only needed for HD based */
651 /* The battery voltage is usually a little lower directly after
652 turning on, because the disk was used heavily. Raise it by 5% */
654 if (!charger_inserted()) /* only if charger not connected */
657 avgbat
+= (percent_to_volt_discharge
[battery_type
][6] -
658 percent_to_volt_discharge
[battery_type
][5]) / 2;
660 #endif /* HAVE_DISK_STORAGE */
662 avgbat
= avgbat
* BATT_AVE_SAMPLES
;
663 battery_millivolts
= avgbat
/ BATT_AVE_SAMPLES
;
664 power_history
[0] = battery_millivolts
;
667 if (charger_inserted()) {
668 battery_percent
= voltage_to_percent(battery_millivolts
,
669 percent_to_volt_charge
);
674 battery_percent
= voltage_to_percent(battery_millivolts
,
675 percent_to_volt_discharge
[battery_type
]);
676 battery_percent
+= battery_percent
< 100;
679 powermgmt_init_target();
681 next_power_hist
= current_tick
+ HZ
*60;
686 unsigned int pwr
= power_input_status();
687 #ifdef HAVE_BATTERY_SWITCH
688 if ((pwr
^ power_thread_inputs
) & POWER_INPUT_BATTERY
) {
690 reset_battery_filter(battery_adc_voltage());
693 power_thread_inputs
= pwr
;
695 if (!detect_charger(pwr
))
696 #endif /* CONFIG_CHARGING */
699 sleep(POWER_THREAD_STEP_TICKS
);
701 /* Do common power tasks */
705 /* Perform target tasks */
706 charging_algorithm_step();
708 if (TIME_BEFORE(current_tick
, next_power_hist
))
711 /* increment to ensure there is a record for every minute
712 * rather than go forward from the current tick */
713 next_power_hist
+= HZ
*60;
715 /* rotate the power history */
716 memmove(&power_history
[1], &power_history
[0],
717 sizeof(power_history
) - sizeof(power_history
[0]));
719 /* insert new value at the start, in millivolts 8-) */
720 power_history
[0] = battery_millivolts
;
722 handle_auto_poweroff();
726 void powermgmt_init(void)
728 /* init history to 0 */
729 memset(power_history
, 0, sizeof(power_history
));
730 create_thread(power_thread
, power_stack
, sizeof(power_stack
), 0,
731 power_thread_name
IF_PRIO(, PRIORITY_SYSTEM
)
735 /* Various hardware housekeeping tasks relating to shutting down the player */
736 void shutdown_hw(void)
738 charging_algorithm_close();
741 if (battery_level_safe()) { /* do not save on critical battery */
742 #ifdef HAVE_LCD_BITMAP
745 if (storage_disk_is_active())
749 while (storage_disk_is_active())
752 #if CONFIG_CODEC == SWCODEC
758 /* If HD is still active we try to wait for spindown, otherwise the
759 shutdown_timeout in power_thread_step will force a power off */
760 while (storage_disk_is_active())
763 #ifndef HAVE_LCD_COLOR
766 #ifdef HAVE_REMOTE_LCD
767 lcd_remote_set_contrast(0);
769 #ifdef HAVE_LCD_SHUTDOWN
773 /* Small delay to make sure all HW gets time to flush. Especially
774 eeprom chips are quite slow and might be still writing the last
780 void sys_poweroff(void)
783 logf("sys_poweroff()");
784 /* If the main thread fails to shut down the system, we will force a
785 power off after an 20 second timeout - 28 seconds if recording */
786 if (shutdown_timeout
== 0) {
787 #if defined(IAUDIO_X5) || defined(IAUDIO_M5)
788 pcf50606_reset_timeout(); /* Reset timer on first attempt only */
790 #ifdef HAVE_RECORDING
791 if (audio_status() & AUDIO_STATUS_RECORD
)
792 shutdown_timeout
+= HZ
*8;
794 shutdown_timeout
+= HZ
*20;
797 queue_broadcast(SYS_POWEROFF
, 0);
798 #endif /* BOOTLOADER */
801 void cancel_shutdown(void)
803 logf("cancel_shutdown()");
805 #if defined(IAUDIO_X5) || defined(IAUDIO_M5)
806 /* TODO: Move some things to target/ tree */
807 if (shutdown_timeout
)
808 pcf50606_reset_timeout();
811 shutdown_timeout
= 0;
813 #endif /* SIMULATOR */
815 /* Send system battery level update events on reaching certain significant
816 levels. This must be called after battery_percent has been updated. */
817 void send_battery_level_event(void)
819 static const int levels
[] = { 5, 15, 30, 50, 0 };
820 const int *level
= levels
;
824 if (battery_percent
<= *level
&& last_sent_battery_level
> *level
) {
825 last_sent_battery_level
= *level
;
826 queue_broadcast(SYS_BATTERY_UPDATE
, last_sent_battery_level
);