Move error message generation out of irivertools.cpp to make it independent from...
[Rockbox.git] / firmware / powermgmt.c
blob026381c2ff3e1483ee8d251e2892b47aa9a6b764
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 * All files in this archive are subject to the GNU General Public License.
14 * See the file COPYING in the source tree root for full license agreement.
16 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
17 * KIND, either express or implied.
19 ****************************************************************************/
20 #include "config.h"
21 #include "cpu.h"
22 #include "kernel.h"
23 #include "thread.h"
24 #include "system.h"
25 #include "debug.h"
26 #include "panic.h"
27 #include "adc.h"
28 #include "string.h"
29 #include "sprintf.h"
30 #include "ata.h"
31 #include "power.h"
32 #include "button.h"
33 #include "audio.h"
34 #include "mp3_playback.h"
35 #include "usb.h"
36 #include "powermgmt.h"
37 #include "backlight.h"
38 #include "lcd.h"
39 #include "rtc.h"
40 #if CONFIG_TUNER
41 #include "fmradio.h"
42 #endif
43 #include "sound.h"
44 #ifdef HAVE_LCD_BITMAP
45 #include "font.h"
46 #endif
47 #if defined(HAVE_RECORDING) && (CONFIG_CODEC == SWCODEC)
48 #include "pcm_record.h"
49 #endif
50 #include "logf.h"
51 #include "lcd-remote.h"
52 #ifdef SIMULATOR
53 #include <time.h>
54 #endif
56 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
57 #include "pcf50606.h"
58 #include "lcd-remote-target.h"
59 #endif
62 * Define DEBUG_FILE to create a csv (spreadsheet) with battery information
63 * in it (one sample per minute). This is only for very low level debug.
65 #undef DEBUG_FILE
66 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
67 #include "file.h"
68 #define DEBUG_FILE_NAME "/powermgmt.csv"
69 #define DEBUG_MESSAGE_LEN 133
70 static char debug_message[DEBUG_MESSAGE_LEN];
71 #define DEBUG_STACK ((0x1000)/sizeof(long))
72 static int fd = -1; /* write debug information to this file */
73 static int wrcount = 0;
74 #else
75 #define DEBUG_STACK 0
76 #endif
78 static int shutdown_timeout = 0;
79 #if CONFIG_CHARGING >= CHARGING_MONITOR
80 charge_state_type charge_state; /* charging mode */
81 #endif
83 static void send_battery_level_event(void);
84 static int last_sent_battery_level = 100;
86 #if CONFIG_CHARGING
87 charger_input_state_type charger_input_state IDATA_ATTR;
88 #endif
90 #ifdef SIMULATOR /***********************************************************/
92 #define BATT_MINMVOLT 2500 /* minimum millivolts of battery */
93 #define BATT_MAXMVOLT 4500 /* maximum millivolts of battery */
94 #define BATT_MAXRUNTIME (10 * 60) /* maximum runtime with full battery in minutes */
96 static unsigned int battery_millivolts = (unsigned int)BATT_MAXMVOLT;
97 static int battery_percent = 100; /* battery capacity level in percent */
98 static int powermgmt_est_runningtime_min = BATT_MAXRUNTIME; /* estimated remaining time in minutes */
100 static void battery_status_update(void)
102 static time_t last_change = 0;
103 static bool charging = false;
104 time_t now;
106 time(&now);
107 if (last_change < now)
109 last_change = now;
111 /* change the values: */
112 if (charging)
114 if (battery_millivolts >= BATT_MAXMVOLT)
116 /* Pretend the charger was disconnected */
117 charging = false;
118 queue_broadcast(SYS_CHARGER_DISCONNECTED, 0);
119 last_sent_battery_level = 100;
122 else
124 if (battery_millivolts <= BATT_MINMVOLT)
126 /* Pretend the charger was connected */
127 charging = true;
128 queue_broadcast(SYS_CHARGER_CONNECTED, 0);
129 last_sent_battery_level = 0;
132 if (charging)
133 battery_millivolts += (BATT_MAXMVOLT - BATT_MINMVOLT) / 50;
134 else
135 battery_millivolts -= (BATT_MAXMVOLT - BATT_MINMVOLT) / 100;
137 battery_percent = 100 * (battery_millivolts - BATT_MINMVOLT) /
138 (BATT_MAXMVOLT - BATT_MINMVOLT);
139 powermgmt_est_runningtime_min = battery_percent * BATT_MAXRUNTIME / 100;
141 send_battery_level_event();
144 void battery_read_info(int *voltage, int *level)
146 battery_status_update();
148 if (voltage)
149 *voltage = battery_millivolts;
151 if (level)
152 *level = battery_percent;
155 unsigned int battery_voltage(void)
157 battery_status_update();
158 return battery_millivolts;
161 int battery_level(void)
163 battery_status_update();
164 return battery_percent;
167 int battery_time(void)
169 battery_status_update();
170 return powermgmt_est_runningtime_min;
173 bool battery_level_safe(void)
175 return battery_level() >= 10;
178 void set_poweroff_timeout(int timeout)
180 (void)timeout;
183 void set_battery_capacity(int capacity)
185 (void)capacity;
188 #if BATTERY_TYPES_COUNT > 1
189 void set_battery_type(int type)
191 (void)type;
193 #endif
195 void reset_poweroff_timer(void)
199 #ifdef HAVE_ACCESSORY_SUPPLY
200 void accessory_supply_set(bool enable)
202 (void)enable;
204 #endif
206 #else /* not SIMULATOR ******************************************************/
208 static void power_thread_sleep(int ticks);
211 * Average battery voltage and charger voltage, filtered via a digital
212 * exponential filter (aka. exponential moving average, scaled):
213 * avgbat = y[n] = (N-1)/N*y[n-1] + x[n]. battery_millivolts = y[n] / N.
215 static unsigned int avgbat; /* average battery voltage (filtering) */
216 static unsigned int battery_millivolts;/* filtered battery voltage, millivolts */
218 /* battery level (0-100%) of this minute, updated once per minute */
219 static int battery_percent = -1;
220 static int battery_capacity = BATTERY_CAPACITY_DEFAULT; /* default value, mAh */
221 #if BATTERY_TYPES_COUNT > 1
222 static int battery_type = 0;
223 #else
224 #define battery_type 0
225 #endif
227 /* Power history: power_history[0] is the newest sample */
228 unsigned short power_history[POWER_HISTORY_LEN];
230 static char power_stack[DEFAULT_STACK_SIZE/2 + DEBUG_STACK];
231 static const char power_thread_name[] = "power";
233 static int poweroff_timeout = 0;
234 static int powermgmt_est_runningtime_min = -1;
236 static bool sleeptimer_active = false;
237 static long sleeptimer_endtick;
239 static long last_event_tick;
241 static int voltage_to_battery_level(int battery_millivolts);
242 static void battery_status_update(void);
243 static int runcurrent(void);
245 void battery_read_info(int *voltage, int *level)
247 int millivolts = battery_adc_voltage();
249 if (voltage)
250 *voltage = millivolts;
252 if (level)
253 *level = voltage_to_battery_level(millivolts);
256 void reset_poweroff_timer(void)
258 last_event_tick = current_tick;
261 #if BATTERY_TYPES_COUNT > 1
262 void set_battery_type(int type)
264 if (type != battery_type) {
265 battery_type = type;
266 battery_status_update(); /* recalculate the battery status */
269 #endif
271 void set_battery_capacity(int capacity)
273 battery_capacity = capacity;
274 if (battery_capacity > BATTERY_CAPACITY_MAX)
275 battery_capacity = BATTERY_CAPACITY_MAX;
276 if (battery_capacity < BATTERY_CAPACITY_MIN)
277 battery_capacity = BATTERY_CAPACITY_MIN;
278 battery_status_update(); /* recalculate the battery status */
281 int battery_time(void)
283 return powermgmt_est_runningtime_min;
286 /* Returns battery level in percent */
287 int battery_level(void)
289 return battery_percent;
292 /* Returns filtered battery voltage [millivolts] */
293 unsigned int battery_voltage(void)
295 return battery_millivolts;
298 /* Tells if the battery level is safe for disk writes */
299 bool battery_level_safe(void)
301 return battery_millivolts > battery_level_dangerous[battery_type];
304 void set_poweroff_timeout(int timeout)
306 poweroff_timeout = timeout;
309 void set_sleep_timer(int seconds)
311 if(seconds) {
312 sleeptimer_active = true;
313 sleeptimer_endtick = current_tick + seconds * HZ;
315 else {
316 sleeptimer_active = false;
317 sleeptimer_endtick = 0;
321 int get_sleep_timer(void)
323 if(sleeptimer_active)
324 return (sleeptimer_endtick - current_tick) / HZ;
325 else
326 return 0;
329 /* look into the percent_to_volt_* table and get a realistic battery level */
330 static int voltage_to_percent(int voltage, const short* table)
332 if (voltage <= table[0])
333 return 0;
334 else
335 if (voltage >= table[10])
336 return 100;
337 else {
338 /* search nearest value */
339 int i = 0;
340 while ((i < 10) && (table[i+1] < voltage))
341 i++;
342 /* interpolate linear between the smaller and greater value */
343 return (i * 10) /* Tens digit, 10% per entry */
344 + (((voltage - table[i]) * 10)
345 / (table[i+1] - table[i])); /* Ones digit: interpolated */
349 /* update battery level and estimated runtime, called once per minute or
350 * when battery capacity / type settings are changed */
351 static int voltage_to_battery_level(int battery_millivolts)
353 int level;
355 #if CONFIG_CHARGING >= CHARGING_MONITOR
356 if (charge_state == DISCHARGING) {
357 level = voltage_to_percent(battery_millivolts,
358 percent_to_volt_discharge[battery_type]);
360 else if (charge_state == CHARGING) {
361 /* battery level is defined to be < 100% until charging is finished */
362 level = MIN(voltage_to_percent(battery_millivolts,
363 percent_to_volt_charge), 99);
365 else { /* in topoff/trickle charge, battery is by definition 100% full */
366 level = 100;
368 #else
369 /* always use the discharge table */
370 level = voltage_to_percent(battery_millivolts,
371 percent_to_volt_discharge[battery_type]);
372 #endif /* CONFIG_CHARGING ... */
374 return level;
377 static void battery_status_update(void)
379 int level = voltage_to_battery_level(battery_millivolts);
381 /* calculate estimated remaining running time */
382 /* discharging: remaining running time */
383 /* charging: remaining charging time */
384 #if CONFIG_CHARGING >= CHARGING_MONITOR
385 if (charge_state == CHARGING) {
386 powermgmt_est_runningtime_min = (100 - level) * battery_capacity * 60
387 / 100 / (CURRENT_MAX_CHG - runcurrent());
389 else
390 #endif
392 if ((battery_millivolts + 20) > percent_to_volt_discharge[0][0])
393 powermgmt_est_runningtime_min = (level + battery_percent) * 60 *
394 battery_capacity / 200 / runcurrent();
396 else if (battery_millivolts <= battery_level_shutoff[0])
397 powermgmt_est_runningtime_min = 0;
399 else
400 powermgmt_est_runningtime_min = (battery_millivolts -
401 battery_level_shutoff[0]) / 2;
404 battery_percent = level;
405 send_battery_level_event();
409 * We shut off in the following cases:
410 * 1) The unit is idle, not playing music
411 * 2) The unit is playing music, but is paused
412 * 3) The battery level has reached shutdown limit
414 * We do not shut off in the following cases:
415 * 1) The USB is connected
416 * 2) The charger is connected
417 * 3) We are recording, or recording with pause
418 * 4) The radio is playing
420 static void handle_auto_poweroff(void)
422 long timeout = poweroff_timeout*60*HZ;
423 int audio_stat = audio_status();
425 #if CONFIG_CHARGING
427 * Inhibit shutdown as long as the charger is plugged in. If it is
428 * unplugged, wait for a timeout period and then shut down.
430 if(charger_input_state == CHARGER || audio_stat == AUDIO_STATUS_PLAY) {
431 last_event_tick = current_tick;
433 #endif
435 #ifndef NO_LOW_BATTERY_SHUTDOWN
436 /* switch off unit if battery level is too low for reliable operation */
437 if(battery_millivolts < battery_level_shutoff[battery_type]) {
438 if(!shutdown_timeout) {
439 backlight_on();
440 sys_poweroff();
443 #endif
445 if(timeout &&
446 #if CONFIG_TUNER && !defined(BOOTLOADER)
447 (!(get_radio_status() & FMRADIO_PLAYING)) &&
448 #endif
449 !usb_inserted() &&
450 ((audio_stat == 0) ||
451 ((audio_stat == (AUDIO_STATUS_PLAY | AUDIO_STATUS_PAUSE)) &&
452 !sleeptimer_active)))
454 if(TIME_AFTER(current_tick, last_event_tick + timeout) &&
455 TIME_AFTER(current_tick, last_disk_activity + timeout))
457 sys_poweroff();
460 else
462 /* Handle sleeptimer */
463 if(sleeptimer_active && !usb_inserted())
465 if(TIME_AFTER(current_tick, sleeptimer_endtick))
467 audio_stop();
468 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
469 if((charger_input_state == CHARGER) ||
470 (charger_input_state == CHARGER_PLUGGED))
472 DEBUGF("Sleep timer timeout. Stopping...\n");
473 set_sleep_timer(0);
474 backlight_off(); /* Nighty, nighty... */
476 else
477 #endif
479 DEBUGF("Sleep timer timeout. Shutting off...\n");
480 sys_poweroff();
488 * Estimate how much current we are drawing just to run.
490 static int runcurrent(void)
492 int current;
494 #if MEM == 8 && !defined(HAVE_MMC)
495 /* assuming 192 kbps, the running time is 22% longer with 8MB */
496 current = (CURRENT_NORMAL*100/122);
497 #else
498 current = CURRENT_NORMAL;
499 #endif /* MEM == 8 */
501 if(usb_inserted()
502 #if defined(HAVE_USB_POWER)
503 #if (CURRENT_USB < CURRENT_NORMAL)
504 || usb_powered()
505 #else
506 && !usb_powered()
507 #endif
508 #endif
511 current = CURRENT_USB;
514 #if defined(HAVE_BACKLIGHT) && !defined(BOOTLOADER)
515 if (backlight_get_current_timeout() == 0) /* LED always on */
516 current += CURRENT_BACKLIGHT;
517 #endif
519 #if defined(HAVE_RECORDING) && defined(CURRENT_RECORD)
520 if (audio_status() & AUDIO_STATUS_RECORD)
521 current += CURRENT_RECORD;
522 #endif
524 #ifdef HAVE_SPDIF_POWER
525 if (spdif_powered())
526 current += CURRENT_SPDIF_OUT;
527 #endif
529 #ifdef HAVE_REMOTE_LCD
530 if (remote_detect())
531 current += CURRENT_REMOTE;
532 #endif
534 return(current);
538 /* Check to see whether or not we've received an alarm in the last second */
539 #ifdef HAVE_RTC_ALARM
540 static void power_thread_rtc_process(void)
542 if (rtc_check_alarm_flag()) {
543 rtc_enable_alarm(false);
546 #endif
549 * This power thread maintains a history of battery voltage
550 * and implements a charging algorithm.
552 #if CONFIG_CHARGING == CHARGING_CONTROL
553 #define BATT_AVE_SAMPLES 32 /* filter constant / @ 2Hz sample rate */
556 * For a complete description of the charging algorithm read
557 * docs/CHARGING_ALGORITHM.
559 int long_delta; /* long term delta battery voltage */
560 int short_delta; /* short term delta battery voltage */
561 bool disk_activity_last_cycle = false; /* flag set to aid charger time
562 * calculation */
563 char power_message[POWER_MESSAGE_LEN] = ""; /* message that's shown in
564 debug menu */
565 /* percentage at which charging
566 starts */
567 int powermgmt_last_cycle_startstop_min = 0; /* how many minutes ago was the
568 charging started or
569 stopped? */
570 int powermgmt_last_cycle_level = 0; /* which level had the
571 batteries at this time? */
572 int trickle_sec = 0; /* how many seconds should the
573 charger be enabled per
574 minute for trickle
575 charging? */
576 int pid_p = 0; /* PID proportional term */
577 int pid_i = 0; /* PID integral term */
579 static inline void charging_algorithm_small_step(void)
581 if (ata_disk_is_active()) {
582 /* flag hdd use for charging calculation */
583 disk_activity_last_cycle = true;
586 #if defined(DEBUG_FILE)
588 * If we have a lot of pending writes or if the disk is spining,
589 * fsync the debug log file.
591 if((wrcount > 10) || ((wrcount > 0) && ata_disk_is_active())) {
592 fsync(fd);
593 wrcount = 0;
595 #endif /* defined(DEBUG_FILE) */
598 static inline void charging_algorithm_big_step(void)
600 static unsigned int target_voltage = TRICKLE_VOLTAGE; /* desired topoff/trickle
601 * voltage level */
602 static int charge_max_time_idle = 0; /* max. charging duration, calculated at
603 * beginning of charging */
604 static int charge_max_time_now = 0; /* max. charging duration including
605 * hdd activity */
606 static int minutes_disk_activity = 0; /* count minutes of hdd use during
607 * charging */
608 static int last_disk_activity = CHARGE_END_LONGD + 1; /* last hdd use x mins ago */
609 int i;
611 if (charger_input_state == CHARGER_PLUGGED) {
612 pid_p = 0;
613 pid_i = 0;
614 snprintf(power_message, POWER_MESSAGE_LEN, "Charger plugged in");
616 * The charger was just plugged in. If the battery level is
617 * nearly charged, just trickle. If the battery is low, start
618 * a full charge cycle. If the battery level is in between,
619 * top-off and then trickle.
621 if(battery_percent > START_TOPOFF_CHG) {
622 powermgmt_last_cycle_level = battery_percent;
623 powermgmt_last_cycle_startstop_min = 0;
624 if(battery_percent >= START_TRICKLE_CHG) {
625 charge_state = TRICKLE;
626 target_voltage = TRICKLE_VOLTAGE;
627 } else {
628 charge_state = TOPOFF;
629 target_voltage = TOPOFF_VOLTAGE;
631 } else {
633 * Start the charger full strength
635 i = CHARGE_MAX_TIME_1500 * battery_capacity / 1500;
636 charge_max_time_idle =
637 i * (100 + 35 - battery_percent) / 100;
638 if (charge_max_time_idle > i) {
639 charge_max_time_idle = i;
641 charge_max_time_now = charge_max_time_idle;
643 snprintf(power_message, POWER_MESSAGE_LEN,
644 "ChgAt %d%% max %dm", battery_level(),
645 charge_max_time_now);
647 /* enable the charger after the max time calc is done,
648 because battery_level depends on if the charger is
649 on */
650 DEBUGF("power: charger inserted and battery"
651 " not full, charging\n");
652 powermgmt_last_cycle_level = battery_percent;
653 powermgmt_last_cycle_startstop_min = 0;
654 trickle_sec = 60;
655 long_delta = short_delta = 999999;
656 charge_state = CHARGING;
660 if (charge_state == CHARGING) {
661 /* alter charge time max length with extra disk use */
662 if (disk_activity_last_cycle) {
663 minutes_disk_activity++;
664 charge_max_time_now = charge_max_time_idle +
665 (minutes_disk_activity * 2 / 5);
666 disk_activity_last_cycle = false;
667 last_disk_activity = 0;
668 } else {
669 last_disk_activity++;
672 * Check the delta voltage over the last X minutes so we can do
673 * our end-of-charge logic based on the battery level change.
674 *(no longer use minimum time as logic for charge end has 50
675 * minutes minimum charge built in)
677 if (powermgmt_last_cycle_startstop_min > CHARGE_END_SHORTD) {
678 short_delta = power_history[0] -
679 power_history[CHARGE_END_SHORTD - 1];
682 if (powermgmt_last_cycle_startstop_min > CHARGE_END_LONGD) {
684 * Scan the history: the points where measurement is taken need to
685 * be fairly static. (check prior to short delta 'area')
686 * (also only check first and last 10 cycles - delta in middle OK)
688 long_delta = power_history[0] -
689 power_history[CHARGE_END_LONGD - 1];
691 for(i = CHARGE_END_SHORTD; i < CHARGE_END_SHORTD + 10; i++) {
692 if(((power_history[i] - power_history[i+1]) > 50) ||
693 ((power_history[i] - power_history[i+1]) < -50)) {
694 long_delta = 777777;
695 break;
698 for(i = CHARGE_END_LONGD - 11; i < CHARGE_END_LONGD - 1 ; i++) {
699 if(((power_history[i] - power_history[i+1]) > 50) ||
700 ((power_history[i] - power_history[i+1]) < -50)) {
701 long_delta = 888888;
702 break;
707 snprintf(power_message, POWER_MESSAGE_LEN,
708 "Chg %dm, max %dm", powermgmt_last_cycle_startstop_min,
709 charge_max_time_now);
711 * End of charge criteria (any qualify):
712 * 1) Charged a long time
713 * 2) DeltaV went negative for a short time ( & long delta static)
714 * 3) DeltaV was negative over a longer period (no disk use only)
715 * Note: short_delta and long_delta are millivolts
717 if ((powermgmt_last_cycle_startstop_min >= charge_max_time_now) ||
718 (short_delta <= -50 && long_delta < 50 ) || (long_delta < -20 &&
719 last_disk_activity > CHARGE_END_LONGD)) {
720 if (powermgmt_last_cycle_startstop_min > charge_max_time_now) {
721 DEBUGF("power: powermgmt_last_cycle_startstop_min > charge_max_time_now, "
722 "enough!\n");
724 *have charged too long and deltaV detection did not
725 *work!
727 snprintf(power_message, POWER_MESSAGE_LEN,
728 "Chg tmout %d min", charge_max_time_now);
730 * Switch to trickle charging. We skip the top-off
731 * since we've effectively done the top-off operation
732 * already since we charged for the maximum full
733 * charge time.
735 powermgmt_last_cycle_level = battery_percent;
736 powermgmt_last_cycle_startstop_min = 0;
737 charge_state = TRICKLE;
740 * set trickle charge target to a relative voltage instead
741 * of an arbitrary value - the fully charged voltage may
742 * vary according to ambient temp, battery condition etc
743 * trickle target is -0.15v from full voltage acheived
744 * topup target is -0.05v from full voltage
746 target_voltage = power_history[0] - 150;
748 } else {
749 if(short_delta <= -5) {
750 DEBUGF("power: short-term negative"
751 " delta, enough!\n");
752 snprintf(power_message, POWER_MESSAGE_LEN,
753 "end negd %d %dmin", short_delta,
754 powermgmt_last_cycle_startstop_min);
755 target_voltage = power_history[CHARGE_END_SHORTD - 1]
756 - 50;
757 } else {
758 DEBUGF("power: long-term small "
759 "positive delta, enough!\n");
760 snprintf(power_message, POWER_MESSAGE_LEN,
761 "end lowd %d %dmin", long_delta,
762 powermgmt_last_cycle_startstop_min);
763 target_voltage = power_history[CHARGE_END_LONGD - 1]
764 - 50;
767 * Switch to top-off charging.
769 powermgmt_last_cycle_level = battery_percent;
770 powermgmt_last_cycle_startstop_min = 0;
771 charge_state = TOPOFF;
775 else if (charge_state != DISCHARGING) /* top off or trickle */
778 *Time to switch from topoff to trickle?
780 if ((charge_state == TOPOFF) &&
781 (powermgmt_last_cycle_startstop_min > TOPOFF_MAX_TIME))
783 powermgmt_last_cycle_level = battery_percent;
784 powermgmt_last_cycle_startstop_min = 0;
785 charge_state = TRICKLE;
786 target_voltage = target_voltage - 100;
789 * Adjust trickle charge time (proportional and integral terms).
790 * Note: I considered setting the level higher if the USB is
791 * plugged in, but it doesn't appear to be necessary and will
792 * generate more heat [gvb].
795 pid_p = ((signed)target_voltage - (signed)battery_millivolts) / 5;
796 if((pid_p <= PID_DEADZONE) && (pid_p >= -PID_DEADZONE))
797 pid_p = 0;
799 if((unsigned) battery_millivolts < target_voltage) {
800 if(pid_i < 60) {
801 pid_i++; /* limit so it doesn't "wind up" */
803 } else {
804 if(pid_i > 0) {
805 pid_i--; /* limit so it doesn't "wind up" */
809 trickle_sec = pid_p + pid_i;
811 if(trickle_sec > 60) {
812 trickle_sec = 60;
814 if(trickle_sec < 0) {
815 trickle_sec = 0;
818 } else if (charge_state == DISCHARGING) {
819 trickle_sec = 0;
821 * The charger is enabled here only in one case: if it was
822 * turned on at boot time (power_init). Turn it off now.
824 if (charger_enabled)
825 charger_enable(false);
828 if (charger_input_state == CHARGER_UNPLUGGED) {
830 * The charger was just unplugged.
832 DEBUGF("power: charger disconnected, disabling\n");
834 charger_enable(false);
835 powermgmt_last_cycle_level = battery_percent;
836 powermgmt_last_cycle_startstop_min = 0;
837 trickle_sec = 0;
838 pid_p = 0;
839 pid_i = 0;
840 charge_state = DISCHARGING;
841 snprintf(power_message, POWER_MESSAGE_LEN, "Charger: discharge");
844 /* sleep for a minute */
845 if(trickle_sec > 0) {
846 charger_enable(true);
847 power_thread_sleep(HZ * trickle_sec);
849 if(trickle_sec < 60)
850 charger_enable(false);
851 power_thread_sleep(HZ * (60 - trickle_sec));
853 #if defined(DEBUG_FILE)
854 if(usb_inserted()) {
855 if(fd >= 0) {
856 /* It is probably too late to close the file but we can try...*/
857 close(fd);
858 fd = -1;
860 } else {
861 if(fd < 0) {
862 fd = open(DEBUG_FILE_NAME, O_WRONLY | O_APPEND | O_CREAT);
863 if(fd >= 0) {
864 snprintf(debug_message, DEBUG_MESSAGE_LEN,
865 "cycle_min, bat_millivolts, bat_percent, chgr_state"
866 " ,charge_state, pid_p, pid_i, trickle_sec\n");
867 write(fd, debug_message, strlen(debug_message));
868 wrcount = 99; /* force a flush */
871 if(fd >= 0) {
872 snprintf(debug_message, DEBUG_MESSAGE_LEN,
873 "%d, %d, %d, %d, %d, %d, %d, %d\n",
874 powermgmt_last_cycle_startstop_min, battery_millivolts,
875 battery_percent, charger_input_state, charge_state,
876 pid_p, pid_i, trickle_sec);
877 write(fd, debug_message, strlen(debug_message));
878 wrcount++;
881 #endif /* defined(DEBUG_FILE) */
883 powermgmt_last_cycle_startstop_min++;
887 * Prepare charging for poweroff
889 static inline void charging_algorithm_close(void)
891 #if defined(DEBUG_FILE)
892 if(fd >= 0) {
893 close(fd);
894 fd = -1;
896 #endif
898 #else
899 #define BATT_AVE_SAMPLES 128 /* slw filter constant for all others */
901 static inline void charging_algorithm_small_step(void)
903 #if CONFIG_CHARGING == CHARGING_MONITOR
904 switch (charger_input_state)
906 case CHARGER_UNPLUGGED:
907 case NO_CHARGER:
908 charge_state = DISCHARGING;
909 break;
910 case CHARGER_PLUGGED:
911 case CHARGER:
912 if (charging_state()) {
913 charge_state = CHARGING;
914 } else {
915 charge_state = DISCHARGING;
917 break;
919 #endif /* CONFIG_CHARGING == CHARGING_MONITOR */
922 static inline void charging_algorithm_big_step(void)
924 /* sleep for a minute */
925 power_thread_sleep(HZ * 60);
929 * Prepare charging for poweroff
931 static inline void charging_algorithm_close(void)
933 /* Nothing to do */
935 #endif /* CONFIG_CHARGING == CHARGING_CONTROL */
938 * This function is called to do the relativly long sleep waits from within the
939 * main power_thread loop while at the same time servicing any other periodic
940 * functions in the power thread which need to be called at a faster periodic
941 * rate than the slow periodic rate of the main power_thread loop.
943 * While we are waiting for the time to expire, we average the battery
944 * voltages.
946 static void power_thread_sleep(int ticks)
948 int small_ticks;
950 while (ticks > 0) {
952 #if CONFIG_CHARGING
954 * Detect charger plugged/unplugged transitions. On a plugged or
955 * unplugged event, we return immediately, run once through the main
956 * loop (including the subroutines), and end up back here where we
957 * transition to the appropriate steady state charger on/off state.
959 if(charger_inserted()
960 #ifdef HAVE_USB_POWER /* USB powered or USB inserted both provide power */
961 || usb_powered()
962 || (usb_inserted() && usb_charging_enabled())
963 #endif
965 switch(charger_input_state) {
966 case NO_CHARGER:
967 case CHARGER_UNPLUGGED:
968 charger_input_state = CHARGER_PLUGGED;
969 return;
970 case CHARGER_PLUGGED:
971 queue_broadcast(SYS_CHARGER_CONNECTED, 0);
972 last_sent_battery_level = 0;
973 charger_input_state = CHARGER;
974 break;
975 case CHARGER:
976 break;
978 } else { /* charger not inserted */
979 switch(charger_input_state) {
980 case NO_CHARGER:
981 break;
982 case CHARGER_UNPLUGGED:
983 queue_broadcast(SYS_CHARGER_DISCONNECTED, 0);
984 last_sent_battery_level = 100;
985 charger_input_state = NO_CHARGER;
986 break;
987 case CHARGER_PLUGGED:
988 case CHARGER:
989 charger_input_state = CHARGER_UNPLUGGED;
990 return;
993 #endif /* CONFIG_CHARGING */
995 small_ticks = MIN(HZ/2, ticks);
996 sleep(small_ticks);
997 ticks -= small_ticks;
999 /* If the power off timeout expires, the main thread has failed
1000 to shut down the system, and we need to force a power off */
1001 if(shutdown_timeout) {
1002 shutdown_timeout -= small_ticks;
1003 if(shutdown_timeout <= 0)
1004 power_off();
1007 #ifdef HAVE_RTC_ALARM
1008 power_thread_rtc_process();
1009 #endif
1012 * Do a digital exponential filter. We don't sample the battery if
1013 * the disk is spinning unless we are in USB mode (the disk will most
1014 * likely always be spinning in USB mode).
1016 if (!ata_disk_is_active() || usb_inserted()) {
1017 avgbat += battery_adc_voltage() - (avgbat / BATT_AVE_SAMPLES);
1019 * battery_millivolts is the millivolt-scaled filtered battery value.
1021 battery_millivolts = avgbat / BATT_AVE_SAMPLES;
1023 /* update battery status every time an update is available */
1024 battery_status_update();
1026 else if (battery_percent < 8) {
1027 /* If battery is low, observe voltage during disk activity.
1028 * Shut down if voltage drops below shutoff level and we are not
1029 * using NiMH or Alkaline batteries.
1031 battery_millivolts = (battery_adc_voltage() +
1032 battery_millivolts + 1) / 2;
1034 /* update battery status every time an update is available */
1035 battery_status_update();
1037 #ifndef NO_LOW_BATTERY_SHUTDOWN
1038 if (!shutdown_timeout &&
1039 (battery_millivolts < battery_level_shutoff[battery_type]))
1040 sys_poweroff();
1041 else
1042 #endif
1043 avgbat += battery_millivolts - (avgbat / BATT_AVE_SAMPLES);
1046 charging_algorithm_small_step();
1050 static void power_thread(void)
1052 /* Delay reading the first battery level */
1053 #ifdef MROBE_100
1054 while(battery_adc_voltage()>4200) /* gives false readings initially */
1055 #endif
1056 sleep(HZ/100);
1058 /* initialize the voltages for the exponential filter */
1059 avgbat = battery_adc_voltage() + 15;
1061 #ifndef HAVE_MMC /* this adjustment is only needed for HD based */
1062 /* The battery voltage is usually a little lower directly after
1063 turning on, because the disk was used heavily. Raise it by 5% */
1064 #ifdef HAVE_CHARGING
1065 if(!charger_inserted()) /* only if charger not connected */
1066 #endif
1067 avgbat += (percent_to_volt_discharge[battery_type][6] -
1068 percent_to_volt_discharge[battery_type][5]) / 2;
1069 #endif /* not HAVE_MMC */
1071 avgbat = avgbat * BATT_AVE_SAMPLES;
1072 battery_millivolts = avgbat / BATT_AVE_SAMPLES;
1074 #if CONFIG_CHARGING
1075 if(charger_inserted()) {
1076 battery_percent = voltage_to_percent(battery_millivolts,
1077 percent_to_volt_charge);
1078 } else
1079 #endif
1080 { battery_percent = voltage_to_percent(battery_millivolts,
1081 percent_to_volt_discharge[battery_type]);
1082 battery_percent += (battery_percent < 100);
1085 while (1)
1087 /* rotate the power history */
1088 memmove(power_history + 1, power_history,
1089 sizeof(power_history) - sizeof(power_history[0]));
1091 /* insert new value at the start, in millivolts 8-) */
1092 power_history[0] = battery_millivolts;
1094 charging_algorithm_big_step();
1096 handle_auto_poweroff();
1100 void powermgmt_init(void)
1102 /* init history to 0 */
1103 memset(power_history, 0x00, sizeof(power_history));
1104 create_thread(power_thread, power_stack, sizeof(power_stack), 0,
1105 power_thread_name IF_PRIO(, PRIORITY_SYSTEM)
1106 IF_COP(, CPU));
1109 #endif /* SIMULATOR */
1111 void sys_poweroff(void)
1113 logf("sys_poweroff()");
1114 /* If the main thread fails to shut down the system, we will force a
1115 power off after an 20 second timeout - 28 seconds if recording */
1116 if (shutdown_timeout == 0)
1118 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1119 pcf50606_reset_timeout(); /* Reset timer on first attempt only */
1120 #endif
1121 #ifdef HAVE_RECORDING
1122 if (audio_status() & AUDIO_STATUS_RECORD)
1123 shutdown_timeout += HZ*8;
1124 #endif
1125 shutdown_timeout += HZ*20;
1128 queue_broadcast(SYS_POWEROFF, 0);
1131 void cancel_shutdown(void)
1133 logf("sys_cancel_shutdown()");
1135 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1136 /* TODO: Move some things to target/ tree */
1137 if (shutdown_timeout)
1138 pcf50606_reset_timeout();
1139 #endif
1141 shutdown_timeout = 0;
1144 /* Various hardware housekeeping tasks relating to shutting down the jukebox */
1145 void shutdown_hw(void)
1147 #ifndef SIMULATOR
1148 charging_algorithm_close();
1149 audio_stop();
1150 if (battery_level_safe()) { /* do not save on critical battery */
1151 #ifdef HAVE_LCD_BITMAP
1152 glyph_cache_save();
1153 #endif
1154 if(ata_disk_is_active())
1155 ata_spindown(1);
1157 while(ata_disk_is_active())
1158 sleep(HZ/10);
1160 #if CONFIG_CODEC != SWCODEC
1161 mp3_shutdown();
1162 #else
1163 audiohw_close();
1164 #endif
1166 /* If HD is still active we try to wait for spindown, otherwise the
1167 shutdown_timeout in power_thread_sleep will force a power off */
1168 while(ata_disk_is_active())
1169 sleep(HZ/10);
1170 #ifndef IAUDIO_X5
1171 lcd_set_contrast(0);
1172 #endif /* IAUDIO_X5 */
1173 #ifdef HAVE_REMOTE_LCD
1174 lcd_remote_set_contrast(0);
1175 #endif
1177 #ifdef HAVE_LCD_SHUTDOWN
1178 lcd_shutdown();
1179 #endif
1181 /* Small delay to make sure all HW gets time to flush. Especially
1182 eeprom chips are quite slow and might be still writing the last
1183 byte. */
1184 sleep(HZ/4);
1185 power_off();
1186 #endif /* #ifndef SIMULATOR */
1189 /* Send system battery level update events on reaching certain significant
1190 levels. This must be called after battery_percent has been updated. */
1191 static void send_battery_level_event(void)
1193 static const int levels[] = { 5, 15, 30, 50, 0 };
1194 const int *level = levels;
1195 while (*level)
1197 if (battery_percent <= *level && last_sent_battery_level > *level)
1199 last_sent_battery_level = *level;
1200 queue_broadcast(SYS_BATTERY_UPDATE, last_sent_battery_level);
1201 break;
1203 level++;