Fix FS#9110 and its maybe-dupes.
[Rockbox.git] / firmware / powermgmt.c
blob523a62007a95b8ea9c1ae63ab91be48770be3753
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 "cpu.h"
24 #include "kernel.h"
25 #include "thread.h"
26 #include "system.h"
27 #include "debug.h"
28 #include "panic.h"
29 #include "adc.h"
30 #include "string.h"
31 #include "sprintf.h"
32 #include "ata.h"
33 #include "power.h"
34 #include "button.h"
35 #include "audio.h"
36 #include "mp3_playback.h"
37 #include "usb.h"
38 #include "powermgmt.h"
39 #include "backlight.h"
40 #include "lcd.h"
41 #include "rtc.h"
42 #if CONFIG_TUNER
43 #include "fmradio.h"
44 #endif
45 #include "sound.h"
46 #ifdef HAVE_LCD_BITMAP
47 #include "font.h"
48 #endif
49 #if defined(HAVE_RECORDING) && (CONFIG_CODEC == SWCODEC)
50 #include "pcm_record.h"
51 #endif
52 #include "logf.h"
53 #include "lcd-remote.h"
54 #ifdef SIMULATOR
55 #include <time.h>
56 #endif
58 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
59 #include "pcf50606.h"
60 #include "lcd-remote-target.h"
61 #endif
64 * Define DEBUG_FILE to create a csv (spreadsheet) with battery information
65 * in it (one sample per minute). This is only for very low level debug.
67 #undef DEBUG_FILE
68 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
69 #include "file.h"
70 #define DEBUG_FILE_NAME "/powermgmt.csv"
71 #define DEBUG_MESSAGE_LEN 133
72 static char debug_message[DEBUG_MESSAGE_LEN];
73 #define DEBUG_STACK ((0x1000)/sizeof(long))
74 static int fd = -1; /* write debug information to this file */
75 static int wrcount = 0;
76 #else
77 #define DEBUG_STACK 0
78 #endif
80 static int shutdown_timeout = 0;
81 #if CONFIG_CHARGING >= CHARGING_MONITOR
82 charge_state_type charge_state; /* charging mode */
83 #endif
85 static void send_battery_level_event(void);
86 static int last_sent_battery_level = 100;
88 #if CONFIG_CHARGING
89 charger_input_state_type charger_input_state IDATA_ATTR;
90 #endif
92 #ifdef SIMULATOR /***********************************************************/
94 #define BATT_MINMVOLT 2500 /* minimum millivolts of battery */
95 #define BATT_MAXMVOLT 4500 /* maximum millivolts of battery */
96 #define BATT_MAXRUNTIME (10 * 60) /* maximum runtime with full battery in minutes */
98 static unsigned int battery_millivolts = (unsigned int)BATT_MAXMVOLT;
99 static int battery_percent = 100; /* battery capacity level in percent */
100 static int powermgmt_est_runningtime_min = BATT_MAXRUNTIME; /* estimated remaining time in minutes */
102 static void battery_status_update(void)
104 static time_t last_change = 0;
105 static bool charging = false;
106 time_t now;
108 time(&now);
109 if (last_change < now)
111 last_change = now;
113 /* change the values: */
114 if (charging)
116 if (battery_millivolts >= BATT_MAXMVOLT)
118 /* Pretend the charger was disconnected */
119 charging = false;
120 queue_broadcast(SYS_CHARGER_DISCONNECTED, 0);
121 last_sent_battery_level = 100;
124 else
126 if (battery_millivolts <= BATT_MINMVOLT)
128 /* Pretend the charger was connected */
129 charging = true;
130 queue_broadcast(SYS_CHARGER_CONNECTED, 0);
131 last_sent_battery_level = 0;
134 if (charging)
135 battery_millivolts += (BATT_MAXMVOLT - BATT_MINMVOLT) / 50;
136 else
137 battery_millivolts -= (BATT_MAXMVOLT - BATT_MINMVOLT) / 100;
139 battery_percent = 100 * (battery_millivolts - BATT_MINMVOLT) /
140 (BATT_MAXMVOLT - BATT_MINMVOLT);
141 powermgmt_est_runningtime_min = battery_percent * BATT_MAXRUNTIME / 100;
143 send_battery_level_event();
146 void battery_read_info(int *voltage, int *level)
148 battery_status_update();
150 if (voltage)
151 *voltage = battery_millivolts;
153 if (level)
154 *level = battery_percent;
157 unsigned int battery_voltage(void)
159 battery_status_update();
160 return battery_millivolts;
163 int battery_level(void)
165 battery_status_update();
166 return battery_percent;
169 int battery_time(void)
171 battery_status_update();
172 return powermgmt_est_runningtime_min;
175 bool battery_level_safe(void)
177 return battery_level() >= 10;
180 void set_poweroff_timeout(int timeout)
182 (void)timeout;
185 void set_battery_capacity(int capacity)
187 (void)capacity;
190 #if BATTERY_TYPES_COUNT > 1
191 void set_battery_type(int type)
193 (void)type;
195 #endif
197 void reset_poweroff_timer(void)
201 #ifdef HAVE_ACCESSORY_SUPPLY
202 void accessory_supply_set(bool enable)
204 (void)enable;
206 #endif
208 #else /* not SIMULATOR ******************************************************/
210 static void power_thread_sleep(int ticks);
213 * Average battery voltage and charger voltage, filtered via a digital
214 * exponential filter (aka. exponential moving average, scaled):
215 * avgbat = y[n] = (N-1)/N*y[n-1] + x[n]. battery_millivolts = y[n] / N.
217 static unsigned int avgbat; /* average battery voltage (filtering) */
218 static unsigned int battery_millivolts;/* filtered battery voltage, millivolts */
220 /* battery level (0-100%) of this minute, updated once per minute */
221 static int battery_percent = -1;
222 static int battery_capacity = BATTERY_CAPACITY_DEFAULT; /* default value, mAh */
223 #if BATTERY_TYPES_COUNT > 1
224 static int battery_type = 0;
225 #else
226 #define battery_type 0
227 #endif
229 /* Power history: power_history[0] is the newest sample */
230 unsigned short power_history[POWER_HISTORY_LEN];
232 static char power_stack[DEFAULT_STACK_SIZE/2 + DEBUG_STACK];
233 static const char power_thread_name[] = "power";
235 static int poweroff_timeout = 0;
236 static int powermgmt_est_runningtime_min = -1;
238 static bool sleeptimer_active = false;
239 static long sleeptimer_endtick;
241 static long last_event_tick;
243 static int voltage_to_battery_level(int battery_millivolts);
244 static void battery_status_update(void);
245 static int runcurrent(void);
247 void battery_read_info(int *voltage, int *level)
249 int millivolts = battery_adc_voltage();
251 if (voltage)
252 *voltage = millivolts;
254 if (level)
255 *level = voltage_to_battery_level(millivolts);
258 void reset_poweroff_timer(void)
260 last_event_tick = current_tick;
263 #if BATTERY_TYPES_COUNT > 1
264 void set_battery_type(int type)
266 if (type != battery_type) {
267 battery_type = type;
268 battery_status_update(); /* recalculate the battery status */
271 #endif
273 void set_battery_capacity(int capacity)
275 battery_capacity = capacity;
276 if (battery_capacity > BATTERY_CAPACITY_MAX)
277 battery_capacity = BATTERY_CAPACITY_MAX;
278 if (battery_capacity < BATTERY_CAPACITY_MIN)
279 battery_capacity = BATTERY_CAPACITY_MIN;
280 battery_status_update(); /* recalculate the battery status */
283 int battery_time(void)
285 return powermgmt_est_runningtime_min;
288 /* Returns battery level in percent */
289 int battery_level(void)
291 return battery_percent;
294 /* Returns filtered battery voltage [millivolts] */
295 unsigned int battery_voltage(void)
297 return battery_millivolts;
300 /* Tells if the battery level is safe for disk writes */
301 bool battery_level_safe(void)
303 return battery_millivolts > battery_level_dangerous[battery_type];
306 void set_poweroff_timeout(int timeout)
308 poweroff_timeout = timeout;
311 void set_sleep_timer(int seconds)
313 if(seconds) {
314 sleeptimer_active = true;
315 sleeptimer_endtick = current_tick + seconds * HZ;
317 else {
318 sleeptimer_active = false;
319 sleeptimer_endtick = 0;
323 int get_sleep_timer(void)
325 if(sleeptimer_active)
326 return (sleeptimer_endtick - current_tick) / HZ;
327 else
328 return 0;
331 /* look into the percent_to_volt_* table and get a realistic battery level */
332 static int voltage_to_percent(int voltage, const short* table)
334 if (voltage <= table[0])
335 return 0;
336 else
337 if (voltage >= table[10])
338 return 100;
339 else {
340 /* search nearest value */
341 int i = 0;
342 while ((i < 10) && (table[i+1] < voltage))
343 i++;
344 /* interpolate linear between the smaller and greater value */
345 return (i * 10) /* Tens digit, 10% per entry */
346 + (((voltage - table[i]) * 10)
347 / (table[i+1] - table[i])); /* Ones digit: interpolated */
351 /* update battery level and estimated runtime, called once per minute or
352 * when battery capacity / type settings are changed */
353 static int voltage_to_battery_level(int battery_millivolts)
355 int level;
357 #if CONFIG_CHARGING >= CHARGING_MONITOR
358 if (charge_state == DISCHARGING) {
359 level = voltage_to_percent(battery_millivolts,
360 percent_to_volt_discharge[battery_type]);
362 else if (charge_state == CHARGING) {
363 /* battery level is defined to be < 100% until charging is finished */
364 level = MIN(voltage_to_percent(battery_millivolts,
365 percent_to_volt_charge), 99);
367 else { /* in topoff/trickle charge, battery is by definition 100% full */
368 level = 100;
370 #else
371 /* always use the discharge table */
372 level = voltage_to_percent(battery_millivolts,
373 percent_to_volt_discharge[battery_type]);
374 #endif /* CONFIG_CHARGING ... */
376 return level;
379 static void battery_status_update(void)
381 int level = voltage_to_battery_level(battery_millivolts);
383 /* calculate estimated remaining running time */
384 /* discharging: remaining running time */
385 /* charging: remaining charging time */
386 #if CONFIG_CHARGING >= CHARGING_MONITOR
387 if (charge_state == CHARGING) {
388 powermgmt_est_runningtime_min = (100 - level) * battery_capacity * 60
389 / 100 / (CURRENT_MAX_CHG - runcurrent());
391 else
392 #endif
394 if ((battery_millivolts + 20) > percent_to_volt_discharge[0][0])
395 powermgmt_est_runningtime_min = (level + battery_percent) * 60 *
396 battery_capacity / 200 / runcurrent();
398 else if (battery_millivolts <= battery_level_shutoff[0])
399 powermgmt_est_runningtime_min = 0;
401 else
402 powermgmt_est_runningtime_min = (battery_millivolts -
403 battery_level_shutoff[0]) / 2;
406 battery_percent = level;
407 send_battery_level_event();
411 * We shut off in the following cases:
412 * 1) The unit is idle, not playing music
413 * 2) The unit is playing music, but is paused
414 * 3) The battery level has reached shutdown limit
416 * We do not shut off in the following cases:
417 * 1) The USB is connected
418 * 2) The charger is connected
419 * 3) We are recording, or recording with pause
420 * 4) The radio is playing
422 static void handle_auto_poweroff(void)
424 long timeout = poweroff_timeout*60*HZ;
425 int audio_stat = audio_status();
427 #if CONFIG_CHARGING
429 * Inhibit shutdown as long as the charger is plugged in. If it is
430 * unplugged, wait for a timeout period and then shut down.
432 if(charger_input_state == CHARGER || audio_stat == AUDIO_STATUS_PLAY) {
433 last_event_tick = current_tick;
435 #endif
437 #ifndef NO_LOW_BATTERY_SHUTDOWN
438 /* switch off unit if battery level is too low for reliable operation */
439 if(battery_millivolts < battery_level_shutoff[battery_type]) {
440 if(!shutdown_timeout) {
441 backlight_on();
442 sys_poweroff();
445 #endif
447 if(timeout &&
448 #if CONFIG_TUNER && !defined(BOOTLOADER)
449 (!(get_radio_status() & FMRADIO_PLAYING)) &&
450 #endif
451 !usb_inserted() &&
452 ((audio_stat == 0) ||
453 ((audio_stat == (AUDIO_STATUS_PLAY | AUDIO_STATUS_PAUSE)) &&
454 !sleeptimer_active)))
456 if(TIME_AFTER(current_tick, last_event_tick + timeout) &&
457 TIME_AFTER(current_tick, last_disk_activity + timeout))
459 sys_poweroff();
462 else
464 /* Handle sleeptimer */
465 if(sleeptimer_active)
467 if(TIME_AFTER(current_tick, sleeptimer_endtick))
469 audio_stop();
470 if (!usb_inserted()
471 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
472 || ((charger_input_state == CHARGER) ||
473 (charger_input_state == CHARGER_PLUGGED))
474 #endif
477 DEBUGF("Sleep timer timeout. Stopping...\n");
478 set_sleep_timer(0);
479 backlight_off(); /* Nighty, nighty... */
481 else
483 DEBUGF("Sleep timer timeout. Shutting off...\n");
484 sys_poweroff();
492 * Estimate how much current we are drawing just to run.
494 static int runcurrent(void)
496 int current;
498 #if MEM == 8 && !defined(HAVE_MMC)
499 /* assuming 192 kbps, the running time is 22% longer with 8MB */
500 current = (CURRENT_NORMAL*100/122);
501 #else
502 current = CURRENT_NORMAL;
503 #endif /* MEM == 8 */
505 if(usb_inserted()
506 #if defined(HAVE_USB_POWER)
507 #if (CURRENT_USB < CURRENT_NORMAL)
508 || usb_powered()
509 #else
510 && !usb_powered()
511 #endif
512 #endif
515 current = CURRENT_USB;
518 #if defined(HAVE_BACKLIGHT) && !defined(BOOTLOADER)
519 if (backlight_get_current_timeout() == 0) /* LED always on */
520 current += CURRENT_BACKLIGHT;
521 #endif
523 #if defined(HAVE_RECORDING) && defined(CURRENT_RECORD)
524 if (audio_status() & AUDIO_STATUS_RECORD)
525 current += CURRENT_RECORD;
526 #endif
528 #ifdef HAVE_SPDIF_POWER
529 if (spdif_powered())
530 current += CURRENT_SPDIF_OUT;
531 #endif
533 #ifdef HAVE_REMOTE_LCD
534 if (remote_detect())
535 current += CURRENT_REMOTE;
536 #endif
538 return(current);
542 /* Check to see whether or not we've received an alarm in the last second */
543 #ifdef HAVE_RTC_ALARM
544 static void power_thread_rtc_process(void)
546 if (rtc_check_alarm_flag()) {
547 rtc_enable_alarm(false);
550 #endif
553 * This power thread maintains a history of battery voltage
554 * and implements a charging algorithm.
556 #if CONFIG_CHARGING == CHARGING_CONTROL
557 #define BATT_AVE_SAMPLES 32 /* filter constant / @ 2Hz sample rate */
560 * For a complete description of the charging algorithm read
561 * docs/CHARGING_ALGORITHM.
563 int long_delta; /* long term delta battery voltage */
564 int short_delta; /* short term delta battery voltage */
565 bool disk_activity_last_cycle = false; /* flag set to aid charger time
566 * calculation */
567 char power_message[POWER_MESSAGE_LEN] = ""; /* message that's shown in
568 debug menu */
569 /* percentage at which charging
570 starts */
571 int powermgmt_last_cycle_startstop_min = 0; /* how many minutes ago was the
572 charging started or
573 stopped? */
574 int powermgmt_last_cycle_level = 0; /* which level had the
575 batteries at this time? */
576 int trickle_sec = 0; /* how many seconds should the
577 charger be enabled per
578 minute for trickle
579 charging? */
580 int pid_p = 0; /* PID proportional term */
581 int pid_i = 0; /* PID integral term */
583 static inline void charging_algorithm_small_step(void)
585 if (ata_disk_is_active()) {
586 /* flag hdd use for charging calculation */
587 disk_activity_last_cycle = true;
590 #if defined(DEBUG_FILE)
592 * If we have a lot of pending writes or if the disk is spining,
593 * fsync the debug log file.
595 if((wrcount > 10) || ((wrcount > 0) && ata_disk_is_active())) {
596 fsync(fd);
597 wrcount = 0;
599 #endif /* defined(DEBUG_FILE) */
602 static inline void charging_algorithm_big_step(void)
604 static unsigned int target_voltage = TRICKLE_VOLTAGE; /* desired topoff/trickle
605 * voltage level */
606 static int charge_max_time_idle = 0; /* max. charging duration, calculated at
607 * beginning of charging */
608 static int charge_max_time_now = 0; /* max. charging duration including
609 * hdd activity */
610 static int minutes_disk_activity = 0; /* count minutes of hdd use during
611 * charging */
612 static int last_disk_activity = CHARGE_END_LONGD + 1; /* last hdd use x mins ago */
613 int i;
615 if (charger_input_state == CHARGER_PLUGGED) {
616 pid_p = 0;
617 pid_i = 0;
618 snprintf(power_message, POWER_MESSAGE_LEN, "Charger plugged in");
620 * The charger was just plugged in. If the battery level is
621 * nearly charged, just trickle. If the battery is low, start
622 * a full charge cycle. If the battery level is in between,
623 * top-off and then trickle.
625 if(battery_percent > START_TOPOFF_CHG) {
626 powermgmt_last_cycle_level = battery_percent;
627 powermgmt_last_cycle_startstop_min = 0;
628 if(battery_percent >= START_TRICKLE_CHG) {
629 charge_state = TRICKLE;
630 target_voltage = TRICKLE_VOLTAGE;
631 } else {
632 charge_state = TOPOFF;
633 target_voltage = TOPOFF_VOLTAGE;
635 } else {
637 * Start the charger full strength
639 i = CHARGE_MAX_TIME_1500 * battery_capacity / 1500;
640 charge_max_time_idle =
641 i * (100 + 35 - battery_percent) / 100;
642 if (charge_max_time_idle > i) {
643 charge_max_time_idle = i;
645 charge_max_time_now = charge_max_time_idle;
647 snprintf(power_message, POWER_MESSAGE_LEN,
648 "ChgAt %d%% max %dm", battery_level(),
649 charge_max_time_now);
651 /* enable the charger after the max time calc is done,
652 because battery_level depends on if the charger is
653 on */
654 DEBUGF("power: charger inserted and battery"
655 " not full, charging\n");
656 powermgmt_last_cycle_level = battery_percent;
657 powermgmt_last_cycle_startstop_min = 0;
658 trickle_sec = 60;
659 long_delta = short_delta = 999999;
660 charge_state = CHARGING;
664 if (charge_state == CHARGING) {
665 /* alter charge time max length with extra disk use */
666 if (disk_activity_last_cycle) {
667 minutes_disk_activity++;
668 charge_max_time_now = charge_max_time_idle +
669 (minutes_disk_activity * 2 / 5);
670 disk_activity_last_cycle = false;
671 last_disk_activity = 0;
672 } else {
673 last_disk_activity++;
676 * Check the delta voltage over the last X minutes so we can do
677 * our end-of-charge logic based on the battery level change.
678 *(no longer use minimum time as logic for charge end has 50
679 * minutes minimum charge built in)
681 if (powermgmt_last_cycle_startstop_min > CHARGE_END_SHORTD) {
682 short_delta = power_history[0] -
683 power_history[CHARGE_END_SHORTD - 1];
686 if (powermgmt_last_cycle_startstop_min > CHARGE_END_LONGD) {
688 * Scan the history: the points where measurement is taken need to
689 * be fairly static. (check prior to short delta 'area')
690 * (also only check first and last 10 cycles - delta in middle OK)
692 long_delta = power_history[0] -
693 power_history[CHARGE_END_LONGD - 1];
695 for(i = CHARGE_END_SHORTD; i < CHARGE_END_SHORTD + 10; i++) {
696 if(((power_history[i] - power_history[i+1]) > 50) ||
697 ((power_history[i] - power_history[i+1]) < -50)) {
698 long_delta = 777777;
699 break;
702 for(i = CHARGE_END_LONGD - 11; i < CHARGE_END_LONGD - 1 ; i++) {
703 if(((power_history[i] - power_history[i+1]) > 50) ||
704 ((power_history[i] - power_history[i+1]) < -50)) {
705 long_delta = 888888;
706 break;
711 snprintf(power_message, POWER_MESSAGE_LEN,
712 "Chg %dm, max %dm", powermgmt_last_cycle_startstop_min,
713 charge_max_time_now);
715 * End of charge criteria (any qualify):
716 * 1) Charged a long time
717 * 2) DeltaV went negative for a short time ( & long delta static)
718 * 3) DeltaV was negative over a longer period (no disk use only)
719 * Note: short_delta and long_delta are millivolts
721 if ((powermgmt_last_cycle_startstop_min >= charge_max_time_now) ||
722 (short_delta <= -50 && long_delta < 50 ) || (long_delta < -20 &&
723 last_disk_activity > CHARGE_END_LONGD)) {
724 if (powermgmt_last_cycle_startstop_min > charge_max_time_now) {
725 DEBUGF("power: powermgmt_last_cycle_startstop_min > charge_max_time_now, "
726 "enough!\n");
728 *have charged too long and deltaV detection did not
729 *work!
731 snprintf(power_message, POWER_MESSAGE_LEN,
732 "Chg tmout %d min", charge_max_time_now);
734 * Switch to trickle charging. We skip the top-off
735 * since we've effectively done the top-off operation
736 * already since we charged for the maximum full
737 * charge time.
739 powermgmt_last_cycle_level = battery_percent;
740 powermgmt_last_cycle_startstop_min = 0;
741 charge_state = TRICKLE;
744 * set trickle charge target to a relative voltage instead
745 * of an arbitrary value - the fully charged voltage may
746 * vary according to ambient temp, battery condition etc
747 * trickle target is -0.15v from full voltage acheived
748 * topup target is -0.05v from full voltage
750 target_voltage = power_history[0] - 150;
752 } else {
753 if(short_delta <= -5) {
754 DEBUGF("power: short-term negative"
755 " delta, enough!\n");
756 snprintf(power_message, POWER_MESSAGE_LEN,
757 "end negd %d %dmin", short_delta,
758 powermgmt_last_cycle_startstop_min);
759 target_voltage = power_history[CHARGE_END_SHORTD - 1]
760 - 50;
761 } else {
762 DEBUGF("power: long-term small "
763 "positive delta, enough!\n");
764 snprintf(power_message, POWER_MESSAGE_LEN,
765 "end lowd %d %dmin", long_delta,
766 powermgmt_last_cycle_startstop_min);
767 target_voltage = power_history[CHARGE_END_LONGD - 1]
768 - 50;
771 * Switch to top-off charging.
773 powermgmt_last_cycle_level = battery_percent;
774 powermgmt_last_cycle_startstop_min = 0;
775 charge_state = TOPOFF;
779 else if (charge_state != DISCHARGING) /* top off or trickle */
782 *Time to switch from topoff to trickle?
784 if ((charge_state == TOPOFF) &&
785 (powermgmt_last_cycle_startstop_min > TOPOFF_MAX_TIME))
787 powermgmt_last_cycle_level = battery_percent;
788 powermgmt_last_cycle_startstop_min = 0;
789 charge_state = TRICKLE;
790 target_voltage = target_voltage - 100;
793 * Adjust trickle charge time (proportional and integral terms).
794 * Note: I considered setting the level higher if the USB is
795 * plugged in, but it doesn't appear to be necessary and will
796 * generate more heat [gvb].
799 pid_p = ((signed)target_voltage - (signed)battery_millivolts) / 5;
800 if((pid_p <= PID_DEADZONE) && (pid_p >= -PID_DEADZONE))
801 pid_p = 0;
803 if((unsigned) battery_millivolts < target_voltage) {
804 if(pid_i < 60) {
805 pid_i++; /* limit so it doesn't "wind up" */
807 } else {
808 if(pid_i > 0) {
809 pid_i--; /* limit so it doesn't "wind up" */
813 trickle_sec = pid_p + pid_i;
815 if(trickle_sec > 60) {
816 trickle_sec = 60;
818 if(trickle_sec < 0) {
819 trickle_sec = 0;
822 } else if (charge_state == DISCHARGING) {
823 trickle_sec = 0;
825 * The charger is enabled here only in one case: if it was
826 * turned on at boot time (power_init). Turn it off now.
828 if (charger_enabled)
829 charger_enable(false);
832 if (charger_input_state == CHARGER_UNPLUGGED) {
834 * The charger was just unplugged.
836 DEBUGF("power: charger disconnected, disabling\n");
838 charger_enable(false);
839 powermgmt_last_cycle_level = battery_percent;
840 powermgmt_last_cycle_startstop_min = 0;
841 trickle_sec = 0;
842 pid_p = 0;
843 pid_i = 0;
844 charge_state = DISCHARGING;
845 snprintf(power_message, POWER_MESSAGE_LEN, "Charger: discharge");
848 /* sleep for a minute */
849 if(trickle_sec > 0) {
850 charger_enable(true);
851 power_thread_sleep(HZ * trickle_sec);
853 if(trickle_sec < 60)
854 charger_enable(false);
855 power_thread_sleep(HZ * (60 - trickle_sec));
857 #if defined(DEBUG_FILE)
858 if(usb_inserted()) {
859 if(fd >= 0) {
860 /* It is probably too late to close the file but we can try...*/
861 close(fd);
862 fd = -1;
864 } else {
865 if(fd < 0) {
866 fd = open(DEBUG_FILE_NAME, O_WRONLY | O_APPEND | O_CREAT);
867 if(fd >= 0) {
868 snprintf(debug_message, DEBUG_MESSAGE_LEN,
869 "cycle_min, bat_millivolts, bat_percent, chgr_state"
870 " ,charge_state, pid_p, pid_i, trickle_sec\n");
871 write(fd, debug_message, strlen(debug_message));
872 wrcount = 99; /* force a flush */
875 if(fd >= 0) {
876 snprintf(debug_message, DEBUG_MESSAGE_LEN,
877 "%d, %d, %d, %d, %d, %d, %d, %d\n",
878 powermgmt_last_cycle_startstop_min, battery_millivolts,
879 battery_percent, charger_input_state, charge_state,
880 pid_p, pid_i, trickle_sec);
881 write(fd, debug_message, strlen(debug_message));
882 wrcount++;
885 #endif /* defined(DEBUG_FILE) */
887 powermgmt_last_cycle_startstop_min++;
891 * Prepare charging for poweroff
893 static inline void charging_algorithm_close(void)
895 #if defined(DEBUG_FILE)
896 if(fd >= 0) {
897 close(fd);
898 fd = -1;
900 #endif
902 #else
903 #define BATT_AVE_SAMPLES 128 /* slw filter constant for all others */
905 static inline void charging_algorithm_small_step(void)
907 #if CONFIG_CHARGING == CHARGING_MONITOR
908 switch (charger_input_state)
910 case CHARGER_UNPLUGGED:
911 case NO_CHARGER:
912 charge_state = DISCHARGING;
913 break;
914 case CHARGER_PLUGGED:
915 case CHARGER:
916 if (charging_state()) {
917 charge_state = CHARGING;
918 } else {
919 charge_state = DISCHARGING;
921 break;
923 #endif /* CONFIG_CHARGING == CHARGING_MONITOR */
926 static inline void charging_algorithm_big_step(void)
928 /* sleep for a minute */
929 power_thread_sleep(HZ * 60);
933 * Prepare charging for poweroff
935 static inline void charging_algorithm_close(void)
937 /* Nothing to do */
939 #endif /* CONFIG_CHARGING == CHARGING_CONTROL */
942 * This function is called to do the relativly long sleep waits from within the
943 * main power_thread loop while at the same time servicing any other periodic
944 * functions in the power thread which need to be called at a faster periodic
945 * rate than the slow periodic rate of the main power_thread loop.
947 * While we are waiting for the time to expire, we average the battery
948 * voltages.
950 static void power_thread_sleep(int ticks)
952 int small_ticks;
954 while (ticks > 0) {
956 #if CONFIG_CHARGING
958 * Detect charger plugged/unplugged transitions. On a plugged or
959 * unplugged event, we return immediately, run once through the main
960 * loop (including the subroutines), and end up back here where we
961 * transition to the appropriate steady state charger on/off state.
963 if(charger_inserted()
964 #ifdef HAVE_USB_POWER /* USB powered or USB inserted both provide power */
965 || usb_powered()
966 || (usb_inserted() && usb_charging_enabled())
967 #endif
969 switch(charger_input_state) {
970 case NO_CHARGER:
971 case CHARGER_UNPLUGGED:
972 charger_input_state = CHARGER_PLUGGED;
973 return;
974 case CHARGER_PLUGGED:
975 queue_broadcast(SYS_CHARGER_CONNECTED, 0);
976 last_sent_battery_level = 0;
977 charger_input_state = CHARGER;
978 break;
979 case CHARGER:
980 break;
982 } else { /* charger not inserted */
983 switch(charger_input_state) {
984 case NO_CHARGER:
985 break;
986 case CHARGER_UNPLUGGED:
987 queue_broadcast(SYS_CHARGER_DISCONNECTED, 0);
988 last_sent_battery_level = 100;
989 charger_input_state = NO_CHARGER;
990 break;
991 case CHARGER_PLUGGED:
992 case CHARGER:
993 charger_input_state = CHARGER_UNPLUGGED;
994 return;
997 #endif /* CONFIG_CHARGING */
999 small_ticks = MIN(HZ/2, ticks);
1000 sleep(small_ticks);
1001 ticks -= small_ticks;
1003 /* If the power off timeout expires, the main thread has failed
1004 to shut down the system, and we need to force a power off */
1005 if(shutdown_timeout) {
1006 shutdown_timeout -= small_ticks;
1007 if(shutdown_timeout <= 0)
1008 power_off();
1011 #ifdef HAVE_RTC_ALARM
1012 power_thread_rtc_process();
1013 #endif
1016 * Do a digital exponential filter. We don't sample the battery if
1017 * the disk is spinning unless we are in USB mode (the disk will most
1018 * likely always be spinning in USB mode).
1020 if (!ata_disk_is_active() || usb_inserted()) {
1021 avgbat += battery_adc_voltage() - (avgbat / BATT_AVE_SAMPLES);
1023 * battery_millivolts is the millivolt-scaled filtered battery value.
1025 battery_millivolts = avgbat / BATT_AVE_SAMPLES;
1027 /* update battery status every time an update is available */
1028 battery_status_update();
1030 else if (battery_percent < 8) {
1031 /* If battery is low, observe voltage during disk activity.
1032 * Shut down if voltage drops below shutoff level and we are not
1033 * using NiMH or Alkaline batteries.
1035 battery_millivolts = (battery_adc_voltage() +
1036 battery_millivolts + 1) / 2;
1038 /* update battery status every time an update is available */
1039 battery_status_update();
1041 #ifndef NO_LOW_BATTERY_SHUTDOWN
1042 if (!shutdown_timeout &&
1043 (battery_millivolts < battery_level_shutoff[battery_type]))
1044 sys_poweroff();
1045 else
1046 #endif
1047 avgbat += battery_millivolts - (avgbat / BATT_AVE_SAMPLES);
1050 charging_algorithm_small_step();
1054 static void power_thread(void)
1056 /* Delay reading the first battery level */
1057 #ifdef MROBE_100
1058 while(battery_adc_voltage()>4200) /* gives false readings initially */
1059 #endif
1060 sleep(HZ/100);
1062 /* initialize the voltages for the exponential filter */
1063 avgbat = battery_adc_voltage() + 15;
1065 #ifndef HAVE_MMC /* this adjustment is only needed for HD based */
1066 /* The battery voltage is usually a little lower directly after
1067 turning on, because the disk was used heavily. Raise it by 5% */
1068 #ifdef HAVE_CHARGING
1069 if(!charger_inserted()) /* only if charger not connected */
1070 #endif
1071 avgbat += (percent_to_volt_discharge[battery_type][6] -
1072 percent_to_volt_discharge[battery_type][5]) / 2;
1073 #endif /* not HAVE_MMC */
1075 avgbat = avgbat * BATT_AVE_SAMPLES;
1076 battery_millivolts = avgbat / BATT_AVE_SAMPLES;
1078 #if CONFIG_CHARGING
1079 if(charger_inserted()) {
1080 battery_percent = voltage_to_percent(battery_millivolts,
1081 percent_to_volt_charge);
1082 } else
1083 #endif
1084 { battery_percent = voltage_to_percent(battery_millivolts,
1085 percent_to_volt_discharge[battery_type]);
1086 battery_percent += (battery_percent < 100);
1089 while (1)
1091 /* rotate the power history */
1092 memmove(power_history + 1, power_history,
1093 sizeof(power_history) - sizeof(power_history[0]));
1095 /* insert new value at the start, in millivolts 8-) */
1096 power_history[0] = battery_millivolts;
1098 charging_algorithm_big_step();
1100 handle_auto_poweroff();
1104 void powermgmt_init(void)
1106 /* init history to 0 */
1107 memset(power_history, 0x00, sizeof(power_history));
1108 create_thread(power_thread, power_stack, sizeof(power_stack), 0,
1109 power_thread_name IF_PRIO(, PRIORITY_SYSTEM)
1110 IF_COP(, CPU));
1113 #endif /* SIMULATOR */
1115 void sys_poweroff(void)
1117 logf("sys_poweroff()");
1118 /* If the main thread fails to shut down the system, we will force a
1119 power off after an 20 second timeout - 28 seconds if recording */
1120 if (shutdown_timeout == 0)
1122 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1123 pcf50606_reset_timeout(); /* Reset timer on first attempt only */
1124 #endif
1125 #ifdef HAVE_RECORDING
1126 if (audio_status() & AUDIO_STATUS_RECORD)
1127 shutdown_timeout += HZ*8;
1128 #endif
1129 shutdown_timeout += HZ*20;
1132 queue_broadcast(SYS_POWEROFF, 0);
1135 void cancel_shutdown(void)
1137 logf("sys_cancel_shutdown()");
1139 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1140 /* TODO: Move some things to target/ tree */
1141 if (shutdown_timeout)
1142 pcf50606_reset_timeout();
1143 #endif
1145 shutdown_timeout = 0;
1148 /* Various hardware housekeeping tasks relating to shutting down the jukebox */
1149 void shutdown_hw(void)
1151 #ifndef SIMULATOR
1152 charging_algorithm_close();
1153 audio_stop();
1154 if (battery_level_safe()) { /* do not save on critical battery */
1155 #ifdef HAVE_LCD_BITMAP
1156 glyph_cache_save();
1157 #endif
1158 if(ata_disk_is_active())
1159 ata_spindown(1);
1161 while(ata_disk_is_active())
1162 sleep(HZ/10);
1164 #if CONFIG_CODEC != SWCODEC
1165 mp3_shutdown();
1166 #else
1167 audiohw_close();
1168 #endif
1170 /* If HD is still active we try to wait for spindown, otherwise the
1171 shutdown_timeout in power_thread_sleep will force a power off */
1172 while(ata_disk_is_active())
1173 sleep(HZ/10);
1174 #ifndef IAUDIO_X5
1175 lcd_set_contrast(0);
1176 #endif /* IAUDIO_X5 */
1177 #ifdef HAVE_REMOTE_LCD
1178 lcd_remote_set_contrast(0);
1179 #endif
1181 #ifdef HAVE_LCD_SHUTDOWN
1182 lcd_shutdown();
1183 #endif
1185 /* Small delay to make sure all HW gets time to flush. Especially
1186 eeprom chips are quite slow and might be still writing the last
1187 byte. */
1188 sleep(HZ/4);
1189 power_off();
1190 #endif /* #ifndef SIMULATOR */
1193 /* Send system battery level update events on reaching certain significant
1194 levels. This must be called after battery_percent has been updated. */
1195 static void send_battery_level_event(void)
1197 static const int levels[] = { 5, 15, 30, 50, 0 };
1198 const int *level = levels;
1199 while (*level)
1201 if (battery_percent <= *level && last_sent_battery_level > *level)
1203 last_sent_battery_level = *level;
1204 queue_broadcast(SYS_BATTERY_UPDATE, last_sent_battery_level);
1205 break;
1207 level++;