GCC suggests parentheses so give it some (aka fix yellow).
[kugel-rb.git] / firmware / powermgmt.c
blob3fc216080be389b0a8cc056cdd591c8cbb086d09
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
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 ****************************************************************************/
22 #include "config.h"
23 #include "system.h"
24 #include "kernel.h"
25 #include "thread.h"
26 #include "debug.h"
27 #include "adc.h"
28 #include "string.h"
29 #include "storage.h"
30 #include "power.h"
31 #include "audio.h"
32 #include "mp3_playback.h"
33 #include "usb.h"
34 #include "powermgmt.h"
35 #include "backlight.h"
36 #include "lcd.h"
37 #include "rtc.h"
38 #if CONFIG_TUNER
39 #include "fmradio.h"
40 #endif
41 #include "sound.h"
42 #ifdef HAVE_LCD_BITMAP
43 #include "font.h"
44 #endif
45 #include "logf.h"
46 #include "lcd-remote.h"
47 #ifdef SIMULATOR
48 #include <time.h>
49 #endif
51 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
52 #include "pcf50606.h"
53 #include "lcd-remote-target.h"
54 #endif
56 /** Shared by sim **/
57 int last_sent_battery_level = 100;
58 /* battery level (0-100%) */
59 int battery_percent = -1;
60 void send_battery_level_event(void);
62 #if CONFIG_CHARGING
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;
70 #endif
71 #endif /* CONFIG_CHARGING */
73 #ifndef SIMULATOR
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;
89 #else
90 #define battery_type 0
91 #endif
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();
115 if (voltage)
116 *voltage = millivolts;
118 if (level)
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)
132 type = 0;
134 battery_type = type;
135 battery_status_update(); /* recalculate the battery status */
138 #endif
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)
167 return -1;
168 #endif
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)
182 return true;
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];
187 #else
188 return battery_millivolts > battery_level_dangerous[battery_type];
189 #endif
192 void set_poweroff_timeout(int timeout)
194 poweroff_timeout = timeout;
197 void set_sleep_timer(int seconds)
199 if (seconds) {
200 sleeptimer_active = true;
201 sleeptimer_endtick = current_tick + seconds * HZ;
203 else {
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;
213 else
214 return 0;
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]) {
221 return 0;
223 else if (voltage >= table[10]) {
224 return 100;
226 else {
227 /* search nearest value */
228 int i = 0;
230 while (i < 10 && table[i+1] < voltage)
231 i++;
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)
243 int level;
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);
250 if (level > 99)
251 level = 99;
253 else
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]);
261 return level;
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());
275 else
276 #endif
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;
285 else {
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;
312 #if CONFIG_CHARGING
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;
320 #endif
322 if (!shutdown_timeout && query_force_shutdown()) {
323 backlight_on();
324 sys_poweroff();
327 if (timeout &&
328 #if CONFIG_TUNER
329 !(get_radio_status() & FMRADIO_PLAYING) &&
330 #endif
331 !usb_inserted() &&
332 (audio_stat == 0 ||
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)) {
338 sys_poweroff();
341 else if (sleeptimer_active) {
342 /* Handle sleeptimer */
343 if (TIME_AFTER(tick, sleeptimer_endtick)) {
344 audio_stop();
346 if (usb_inserted()
347 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
348 || charger_input_state != NO_CHARGER
349 #endif
351 DEBUGF("Sleep timer timeout. Stopping...\n");
352 set_sleep_timer(0);
353 backlight_off(); /* Nighty, nighty... */
355 else {
356 DEBUGF("Sleep timer timeout. Shutting off...\n");
357 sys_poweroff();
364 * Estimate how much current we are drawing just to run.
366 static int runcurrent(void)
368 int current;
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;
373 #else
374 current = CURRENT_NORMAL;
375 #endif /* MEM == 8 */
377 #ifndef BOOTLOADER
378 if (usb_inserted()
379 #ifdef HAVE_USB_POWER
380 #if (CURRENT_USB < CURRENT_NORMAL)
381 || usb_powered()
382 #else
383 && !usb_powered()
384 #endif
385 #endif
387 current = CURRENT_USB;
390 #if defined(HAVE_BACKLIGHT)
391 if (backlight_get_current_timeout() == 0) /* LED always on */
392 current += CURRENT_BACKLIGHT;
393 #endif
395 #if defined(HAVE_RECORDING) && defined(CURRENT_RECORD)
396 if (audio_status() & AUDIO_STATUS_RECORD)
397 current += CURRENT_RECORD;
398 #endif
400 #ifdef HAVE_SPDIF_POWER
401 if (spdif_powered())
402 current += CURRENT_SPDIF_OUT;
403 #endif
405 #ifdef HAVE_REMOTE_LCD
406 if (remote_detect())
407 current += CURRENT_REMOTE;
408 #endif
409 #endif /* BOOTLOADER */
411 return current;
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);
422 #endif
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)
428 return false;
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];
433 #else
434 return battery_millivolts < battery_level_shutoff[battery_type];
435 #endif
438 #if defined(HAVE_BATTERY_SWITCH) || defined(HAVE_RESET_BATTERY_FILTER)
440 * Reset the battery voltage filter to a new value and update the
441 * status.
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)
455 /* Nothing to do */
458 static inline void charging_algorithm_step(void)
460 /* Nothing to do */
463 static inline void charging_algorithm_close(void)
465 /* Nothing to do */
467 #elif CONFIG_CHARGING == CHARGING_MONITOR
469 * Monitor CHARGING/DISCHARGING state.
471 static inline void powermgmt_init_target(void)
473 /* Nothing to do */
476 static inline void charging_algorithm_step(void)
478 switch (charger_input_state)
480 case CHARGER_PLUGGED:
481 case CHARGER:
482 if (charging_state()) {
483 charge_state = CHARGING;
484 break;
486 /* Fallthrough */
487 case CHARGER_UNPLUGGED:
488 case NO_CHARGER:
489 charge_state = DISCHARGING;
490 break;
494 static inline void charging_algorithm_close(void)
496 /* Nothing to do */
498 #endif /* CONFIG_CHARGING == * */
500 #if 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
510 * or not. */
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)
530 case NO_CHARGER:
531 case CHARGER_UNPLUGGED:
532 charger_input_state = CHARGER_PLUGGED;
533 break;
535 case CHARGER_PLUGGED:
536 queue_broadcast(SYS_CHARGER_CONNECTED, 0);
537 last_sent_battery_level = 0;
538 charger_input_state = CHARGER;
539 break;
541 case CHARGER:
542 /* Steady state */
543 return false;
546 else { /* charger not inserted */
547 switch (charger_input_state)
549 case NO_CHARGER:
550 /* Steady state */
551 return false;
553 case CHARGER_UNPLUGGED:
554 queue_broadcast(SYS_CHARGER_DISCONNECTED, 0);
555 last_sent_battery_level = 100;
556 charger_input_state = NO_CHARGER;
557 break;
559 case CHARGER_PLUGGED:
560 case CHARGER:
561 charger_input_state = CHARGER_UNPLUGGED;
562 break;
566 /* Transitional state */
567 return true;
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)
583 power_off();
586 #ifdef HAVE_RTC_ALARM
587 power_thread_rtc_process();
588 #endif
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
598 #endif
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()) {
622 sys_poweroff();
624 else {
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 */
635 #ifdef MROBE_100
636 while (battery_adc_voltage() > 4200) /* gives false readings initially */
637 #endif
639 sleep(HZ/100);
642 #if CONFIG_CHARGING
643 /* Initialize power input status before calling other routines. */
644 power_thread_inputs = power_input_status();
645 #endif
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% */
653 #if CONFIG_CHARGING
654 if (!charger_inserted()) /* only if charger not connected */
655 #endif
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;
666 #if CONFIG_CHARGING
667 if (charger_inserted()) {
668 battery_percent = voltage_to_percent(battery_millivolts,
669 percent_to_volt_charge);
671 else
672 #endif
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;
683 while (1)
685 #if CONFIG_CHARGING
686 unsigned int pwr = power_input_status();
687 #ifdef HAVE_BATTERY_SWITCH
688 if ((pwr ^ power_thread_inputs) & POWER_INPUT_BATTERY) {
689 sleep(HZ/10);
690 reset_battery_filter(battery_adc_voltage());
692 #endif
693 power_thread_inputs = pwr;
695 if (!detect_charger(pwr))
696 #endif /* CONFIG_CHARGING */
698 /* Steady state */
699 sleep(POWER_THREAD_STEP_TICKS);
701 /* Do common power tasks */
702 power_thread_step();
705 /* Perform target tasks */
706 charging_algorithm_step();
708 if (TIME_BEFORE(current_tick, next_power_hist))
709 continue;
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();
724 } /* power_thread */
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)
732 IF_COP(, CPU));
735 /* Various hardware housekeeping tasks relating to shutting down the player */
736 void shutdown_hw(void)
738 charging_algorithm_close();
739 audio_stop();
741 if (battery_level_safe()) { /* do not save on critical battery */
742 #ifdef HAVE_LCD_BITMAP
743 glyph_cache_save();
744 #endif
745 if (storage_disk_is_active())
746 storage_spindown(1);
749 while (storage_disk_is_active())
750 sleep(HZ/10);
752 #if CONFIG_CODEC == SWCODEC
753 audiohw_close();
754 #else
755 mp3_shutdown();
756 #endif
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())
761 sleep(HZ/10);
763 #ifndef HAVE_LCD_COLOR
764 lcd_set_contrast(0);
765 #endif
766 #ifdef HAVE_REMOTE_LCD
767 lcd_remote_set_contrast(0);
768 #endif
769 #ifdef HAVE_LCD_SHUTDOWN
770 lcd_shutdown();
771 #endif
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
775 byte. */
776 sleep(HZ/4);
777 power_off();
780 void sys_poweroff(void)
782 #ifndef BOOTLOADER
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 */
789 #endif
790 #ifdef HAVE_RECORDING
791 if (audio_status() & AUDIO_STATUS_RECORD)
792 shutdown_timeout += HZ*8;
793 #endif
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();
809 #endif
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;
822 while (*level)
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);
827 break;
830 level++;