Remove .a files before running ar, to avoid problems with renamed files remaining...
[kugel-rb.git] / firmware / powermgmt.c
blob6f0c37b3c79044b23499f5d6f82bd013acbc060e
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 "storage.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 #include "logf.h"
50 #include "lcd-remote.h"
51 #ifdef SIMULATOR
52 #include <time.h>
53 #endif
55 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
56 #include "pcf50606.h"
57 #include "lcd-remote-target.h"
58 #endif
61 * Define DEBUG_FILE to create a csv (spreadsheet) with battery information
62 * in it (one sample per minute). This is only for very low level debug.
64 #undef DEBUG_FILE
65 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
66 #include "file.h"
67 #define DEBUG_FILE_NAME "/powermgmt.csv"
68 #define DEBUG_MESSAGE_LEN 133
69 static char debug_message[DEBUG_MESSAGE_LEN];
70 #define DEBUG_STACK ((0x1000)/sizeof(long))
71 static int fd = -1; /* write debug information to this file */
72 static int wrcount = 0;
73 #else
74 #define DEBUG_STACK 0
75 #endif
77 static int shutdown_timeout = 0;
78 #if CONFIG_CHARGING >= CHARGING_MONITOR
79 charge_state_type charge_state; /* charging mode */
80 #endif
82 static void send_battery_level_event(void);
83 static int last_sent_battery_level = 100;
85 #if CONFIG_CHARGING
86 charger_input_state_type charger_input_state IDATA_ATTR;
87 #endif
89 #ifdef SIMULATOR /***********************************************************/
91 #define BATT_MINMVOLT 2500 /* minimum millivolts of battery */
92 #define BATT_MAXMVOLT 4500 /* maximum millivolts of battery */
93 #define BATT_MAXRUNTIME (10 * 60) /* maximum runtime with full battery in minutes */
95 static unsigned int battery_millivolts = (unsigned int)BATT_MAXMVOLT;
96 static int battery_percent = 100; /* battery capacity level in percent */
97 static int powermgmt_est_runningtime_min = BATT_MAXRUNTIME; /* estimated remaining time in minutes */
99 static void battery_status_update(void)
101 static time_t last_change = 0;
102 static bool charging = false;
103 time_t now;
105 time(&now);
106 if (last_change < now)
108 last_change = now;
110 /* change the values: */
111 if (charging)
113 if (battery_millivolts >= BATT_MAXMVOLT)
115 /* Pretend the charger was disconnected */
116 charging = false;
117 queue_broadcast(SYS_CHARGER_DISCONNECTED, 0);
118 last_sent_battery_level = 100;
121 else
123 if (battery_millivolts <= BATT_MINMVOLT)
125 /* Pretend the charger was connected */
126 charging = true;
127 queue_broadcast(SYS_CHARGER_CONNECTED, 0);
128 last_sent_battery_level = 0;
131 if (charging)
132 battery_millivolts += (BATT_MAXMVOLT - BATT_MINMVOLT) / 50;
133 else
134 battery_millivolts -= (BATT_MAXMVOLT - BATT_MINMVOLT) / 100;
136 battery_percent = 100 * (battery_millivolts - BATT_MINMVOLT) /
137 (BATT_MAXMVOLT - BATT_MINMVOLT);
138 powermgmt_est_runningtime_min = battery_percent * BATT_MAXRUNTIME / 100;
140 send_battery_level_event();
143 void battery_read_info(int *voltage, int *level)
145 battery_status_update();
147 if (voltage)
148 *voltage = battery_millivolts;
150 if (level)
151 *level = battery_percent;
154 unsigned int battery_voltage(void)
156 battery_status_update();
157 return battery_millivolts;
160 int battery_level(void)
162 battery_status_update();
163 return battery_percent;
166 int battery_time(void)
168 battery_status_update();
169 return powermgmt_est_runningtime_min;
172 bool battery_level_safe(void)
174 return battery_level() >= 10;
177 void set_poweroff_timeout(int timeout)
179 (void)timeout;
182 void set_battery_capacity(int capacity)
184 (void)capacity;
187 #if BATTERY_TYPES_COUNT > 1
188 void set_battery_type(int type)
190 (void)type;
192 #endif
194 void reset_poweroff_timer(void)
198 #ifdef HAVE_ACCESSORY_SUPPLY
199 void accessory_supply_set(bool enable)
201 (void)enable;
203 #endif
205 #else /* not SIMULATOR ******************************************************/
207 static void power_thread_sleep(int ticks);
210 * Average battery voltage and charger voltage, filtered via a digital
211 * exponential filter (aka. exponential moving average, scaled):
212 * avgbat = y[n] = (N-1)/N*y[n-1] + x[n]. battery_millivolts = y[n] / N.
214 static unsigned int avgbat; /* average battery voltage (filtering) */
215 static unsigned int battery_millivolts;/* filtered battery voltage, millivolts */
217 /* battery level (0-100%) of this minute, updated once per minute */
218 static int battery_percent = -1;
219 static int battery_capacity = BATTERY_CAPACITY_DEFAULT; /* default value, mAh */
220 #if BATTERY_TYPES_COUNT > 1
221 static int battery_type = 0;
222 #else
223 #define battery_type 0
224 #endif
226 /* Power history: power_history[0] is the newest sample */
227 unsigned short power_history[POWER_HISTORY_LEN];
229 static char power_stack[DEFAULT_STACK_SIZE/2 + DEBUG_STACK];
230 static const char power_thread_name[] = "power";
232 static int poweroff_timeout = 0;
233 static int powermgmt_est_runningtime_min = -1;
235 static bool sleeptimer_active = false;
236 static long sleeptimer_endtick;
238 static long last_event_tick;
240 static int voltage_to_battery_level(int battery_millivolts);
241 static void battery_status_update(void);
242 static int runcurrent(void);
244 void battery_read_info(int *voltage, int *level)
246 int millivolts = battery_adc_voltage();
248 if (voltage)
249 *voltage = millivolts;
251 if (level)
252 *level = voltage_to_battery_level(millivolts);
255 void reset_poweroff_timer(void)
257 last_event_tick = current_tick;
260 #if BATTERY_TYPES_COUNT > 1
261 void set_battery_type(int type)
263 if (type != battery_type) {
264 battery_type = type;
265 battery_status_update(); /* recalculate the battery status */
268 #endif
270 void set_battery_capacity(int capacity)
272 battery_capacity = capacity;
273 if (battery_capacity > BATTERY_CAPACITY_MAX)
274 battery_capacity = BATTERY_CAPACITY_MAX;
275 if (battery_capacity < BATTERY_CAPACITY_MIN)
276 battery_capacity = BATTERY_CAPACITY_MIN;
277 battery_status_update(); /* recalculate the battery status */
280 int battery_time(void)
282 return powermgmt_est_runningtime_min;
285 /* Returns battery level in percent */
286 int battery_level(void)
288 return battery_percent;
291 /* Returns filtered battery voltage [millivolts] */
292 unsigned int battery_voltage(void)
294 return battery_millivolts;
297 /* Tells if the battery level is safe for disk writes */
298 bool battery_level_safe(void)
300 return battery_millivolts > battery_level_dangerous[battery_type];
303 void set_poweroff_timeout(int timeout)
305 poweroff_timeout = timeout;
308 void set_sleep_timer(int seconds)
310 if(seconds) {
311 sleeptimer_active = true;
312 sleeptimer_endtick = current_tick + seconds * HZ;
314 else {
315 sleeptimer_active = false;
316 sleeptimer_endtick = 0;
320 int get_sleep_timer(void)
322 if(sleeptimer_active)
323 return (sleeptimer_endtick - current_tick) / HZ;
324 else
325 return 0;
328 /* look into the percent_to_volt_* table and get a realistic battery level */
329 static int voltage_to_percent(int voltage, const short* table)
331 if (voltage <= table[0])
332 return 0;
333 else
334 if (voltage >= table[10])
335 return 100;
336 else {
337 /* search nearest value */
338 int i = 0;
339 while ((i < 10) && (table[i+1] < voltage))
340 i++;
341 /* interpolate linear between the smaller and greater value */
342 return (i * 10) /* Tens digit, 10% per entry */
343 + (((voltage - table[i]) * 10)
344 / (table[i+1] - table[i])); /* Ones digit: interpolated */
348 /* update battery level and estimated runtime, called once per minute or
349 * when battery capacity / type settings are changed */
350 static int voltage_to_battery_level(int battery_millivolts)
352 int level;
354 #if CONFIG_CHARGING >= CHARGING_MONITOR
355 if (charge_state == DISCHARGING) {
356 level = voltage_to_percent(battery_millivolts,
357 percent_to_volt_discharge[battery_type]);
359 else if (charge_state == CHARGING) {
360 /* battery level is defined to be < 100% until charging is finished */
361 level = MIN(voltage_to_percent(battery_millivolts,
362 percent_to_volt_charge), 99);
364 else { /* in topoff/trickle charge, battery is by definition 100% full */
365 level = 100;
367 #else
368 /* always use the discharge table */
369 level = voltage_to_percent(battery_millivolts,
370 percent_to_volt_discharge[battery_type]);
371 #endif /* CONFIG_CHARGING ... */
373 return level;
376 static void battery_status_update(void)
378 int level = voltage_to_battery_level(battery_millivolts);
380 /* calculate estimated remaining running time */
381 /* discharging: remaining running time */
382 /* charging: remaining charging time */
383 #if CONFIG_CHARGING >= CHARGING_MONITOR
384 if (charge_state == CHARGING) {
385 powermgmt_est_runningtime_min = (100 - level) * battery_capacity * 60
386 / 100 / (CURRENT_MAX_CHG - runcurrent());
388 else
389 #endif
391 if ((battery_millivolts + 20) > percent_to_volt_discharge[0][0])
392 powermgmt_est_runningtime_min = (level + battery_percent) * 60 *
393 battery_capacity / 200 / runcurrent();
395 else if (battery_millivolts <= battery_level_shutoff[0])
396 powermgmt_est_runningtime_min = 0;
398 else
399 powermgmt_est_runningtime_min = (battery_millivolts -
400 battery_level_shutoff[0]) / 2;
403 battery_percent = level;
404 send_battery_level_event();
408 * We shut off in the following cases:
409 * 1) The unit is idle, not playing music
410 * 2) The unit is playing music, but is paused
411 * 3) The battery level has reached shutdown limit
413 * We do not shut off in the following cases:
414 * 1) The USB is connected
415 * 2) The charger is connected
416 * 3) We are recording, or recording with pause
417 * 4) The radio is playing
419 static void handle_auto_poweroff(void)
421 long timeout = poweroff_timeout*60*HZ;
422 int audio_stat = audio_status();
424 #if CONFIG_CHARGING
426 * Inhibit shutdown as long as the charger is plugged in. If it is
427 * unplugged, wait for a timeout period and then shut down.
429 if(charger_input_state == CHARGER || audio_stat == AUDIO_STATUS_PLAY) {
430 last_event_tick = current_tick;
432 #endif
434 #ifndef NO_LOW_BATTERY_SHUTDOWN
435 /* switch off unit if battery level is too low for reliable operation */
436 if(battery_millivolts < battery_level_shutoff[battery_type]) {
437 if(!shutdown_timeout) {
438 backlight_on();
439 sys_poweroff();
442 #endif
444 if(timeout &&
445 #if CONFIG_TUNER && !defined(BOOTLOADER)
446 (!(get_radio_status() & FMRADIO_PLAYING)) &&
447 #endif
448 !usb_inserted() &&
449 ((audio_stat == 0) ||
450 ((audio_stat == (AUDIO_STATUS_PLAY | AUDIO_STATUS_PAUSE)) &&
451 !sleeptimer_active)))
453 if(TIME_AFTER(current_tick, last_event_tick + timeout) &&
454 TIME_AFTER(current_tick, storage_last_disk_activity() + timeout))
456 sys_poweroff();
459 else
461 /* Handle sleeptimer */
462 if(sleeptimer_active)
464 if(TIME_AFTER(current_tick, sleeptimer_endtick))
466 audio_stop();
467 if (usb_inserted()
468 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
469 || ((charger_input_state == CHARGER) ||
470 (charger_input_state == CHARGER_PLUGGED))
471 #endif
474 DEBUGF("Sleep timer timeout. Stopping...\n");
475 set_sleep_timer(0);
476 backlight_off(); /* Nighty, nighty... */
478 else
480 DEBUGF("Sleep timer timeout. Shutting off...\n");
481 sys_poweroff();
489 * Estimate how much current we are drawing just to run.
491 static int runcurrent(void)
493 int current;
495 #if MEM == 8 && !(defined(ARCHOS_ONDIOSP) || defined(ARCHOS_ONDIOFM))
496 /* assuming 192 kbps, the running time is 22% longer with 8MB */
497 current = (CURRENT_NORMAL*100/122);
498 #else
499 current = CURRENT_NORMAL;
500 #endif /* MEM == 8 */
502 if(usb_inserted()
503 #if defined(HAVE_USB_POWER)
504 #if (CURRENT_USB < CURRENT_NORMAL)
505 || usb_powered()
506 #else
507 && !usb_powered()
508 #endif
509 #endif
512 current = CURRENT_USB;
515 #if defined(HAVE_BACKLIGHT) && !defined(BOOTLOADER)
516 if (backlight_get_current_timeout() == 0) /* LED always on */
517 current += CURRENT_BACKLIGHT;
518 #endif
520 #if defined(HAVE_RECORDING) && defined(CURRENT_RECORD)
521 if (audio_status() & AUDIO_STATUS_RECORD)
522 current += CURRENT_RECORD;
523 #endif
525 #ifdef HAVE_SPDIF_POWER
526 if (spdif_powered())
527 current += CURRENT_SPDIF_OUT;
528 #endif
530 #ifdef HAVE_REMOTE_LCD
531 if (remote_detect())
532 current += CURRENT_REMOTE;
533 #endif
535 return(current);
539 /* Check to see whether or not we've received an alarm in the last second */
540 #ifdef HAVE_RTC_ALARM
541 static void power_thread_rtc_process(void)
543 if (rtc_check_alarm_flag()) {
544 rtc_enable_alarm(false);
547 #endif
550 * This power thread maintains a history of battery voltage
551 * and implements a charging algorithm.
553 #if CONFIG_CHARGING == CHARGING_CONTROL
554 #define BATT_AVE_SAMPLES 32 /* filter constant / @ 2Hz sample rate */
557 * For a complete description of the charging algorithm read
558 * docs/CHARGING_ALGORITHM.
560 int long_delta; /* long term delta battery voltage */
561 int short_delta; /* short term delta battery voltage */
562 bool disk_activity_last_cycle = false; /* flag set to aid charger time
563 * calculation */
564 char power_message[POWER_MESSAGE_LEN] = ""; /* message that's shown in
565 debug menu */
566 /* percentage at which charging
567 starts */
568 int powermgmt_last_cycle_startstop_min = 0; /* how many minutes ago was the
569 charging started or
570 stopped? */
571 int powermgmt_last_cycle_level = 0; /* which level had the
572 batteries at this time? */
573 int trickle_sec = 0; /* how many seconds should the
574 charger be enabled per
575 minute for trickle
576 charging? */
577 int pid_p = 0; /* PID proportional term */
578 int pid_i = 0; /* PID integral term */
580 static inline void charging_algorithm_small_step(void)
582 if (storage_disk_is_active()) {
583 /* flag hdd use for charging calculation */
584 disk_activity_last_cycle = true;
587 #if defined(DEBUG_FILE)
589 * If we have a lot of pending writes or if the disk is spining,
590 * fsync the debug log file.
592 if((wrcount > 10) || ((wrcount > 0) && storage_disk_is_active())) {
593 fsync(fd);
594 wrcount = 0;
596 #endif /* defined(DEBUG_FILE) */
599 static inline void charging_algorithm_big_step(void)
601 static unsigned int target_voltage = TRICKLE_VOLTAGE; /* desired topoff/trickle
602 * voltage level */
603 static int charge_max_time_idle = 0; /* max. charging duration, calculated at
604 * beginning of charging */
605 static int charge_max_time_now = 0; /* max. charging duration including
606 * hdd activity */
607 static int minutes_disk_activity = 0; /* count minutes of hdd use during
608 * charging */
609 static int last_disk_activity = CHARGE_END_LONGD + 1; /* last hdd use x mins ago */
610 int i;
612 if (charger_input_state == CHARGER_PLUGGED) {
613 pid_p = 0;
614 pid_i = 0;
615 snprintf(power_message, POWER_MESSAGE_LEN, "Charger plugged in");
617 * The charger was just plugged in. If the battery level is
618 * nearly charged, just trickle. If the battery is low, start
619 * a full charge cycle. If the battery level is in between,
620 * top-off and then trickle.
622 if(battery_percent > START_TOPOFF_CHG) {
623 powermgmt_last_cycle_level = battery_percent;
624 powermgmt_last_cycle_startstop_min = 0;
625 if(battery_percent >= START_TRICKLE_CHG) {
626 charge_state = TRICKLE;
627 target_voltage = TRICKLE_VOLTAGE;
628 } else {
629 charge_state = TOPOFF;
630 target_voltage = TOPOFF_VOLTAGE;
632 } else {
634 * Start the charger full strength
636 i = CHARGE_MAX_TIME_1500 * battery_capacity / 1500;
637 charge_max_time_idle =
638 i * (100 + 35 - battery_percent) / 100;
639 if (charge_max_time_idle > i) {
640 charge_max_time_idle = i;
642 charge_max_time_now = charge_max_time_idle;
644 snprintf(power_message, POWER_MESSAGE_LEN,
645 "ChgAt %d%% max %dm", battery_level(),
646 charge_max_time_now);
648 /* enable the charger after the max time calc is done,
649 because battery_level depends on if the charger is
650 on */
651 DEBUGF("power: charger inserted and battery"
652 " not full, charging\n");
653 powermgmt_last_cycle_level = battery_percent;
654 powermgmt_last_cycle_startstop_min = 0;
655 trickle_sec = 60;
656 long_delta = short_delta = 999999;
657 charge_state = CHARGING;
661 if (charge_state == CHARGING) {
662 /* alter charge time max length with extra disk use */
663 if (disk_activity_last_cycle) {
664 minutes_disk_activity++;
665 charge_max_time_now = charge_max_time_idle +
666 (minutes_disk_activity * 2 / 5);
667 disk_activity_last_cycle = false;
668 last_disk_activity = 0;
669 } else {
670 last_disk_activity++;
673 * Check the delta voltage over the last X minutes so we can do
674 * our end-of-charge logic based on the battery level change.
675 *(no longer use minimum time as logic for charge end has 50
676 * minutes minimum charge built in)
678 if (powermgmt_last_cycle_startstop_min > CHARGE_END_SHORTD) {
679 short_delta = power_history[0] -
680 power_history[CHARGE_END_SHORTD - 1];
683 if (powermgmt_last_cycle_startstop_min > CHARGE_END_LONGD) {
685 * Scan the history: the points where measurement is taken need to
686 * be fairly static. (check prior to short delta 'area')
687 * (also only check first and last 10 cycles - delta in middle OK)
689 long_delta = power_history[0] -
690 power_history[CHARGE_END_LONGD - 1];
692 for(i = CHARGE_END_SHORTD; i < CHARGE_END_SHORTD + 10; i++) {
693 if(((power_history[i] - power_history[i+1]) > 50) ||
694 ((power_history[i] - power_history[i+1]) < -50)) {
695 long_delta = 777777;
696 break;
699 for(i = CHARGE_END_LONGD - 11; i < CHARGE_END_LONGD - 1 ; i++) {
700 if(((power_history[i] - power_history[i+1]) > 50) ||
701 ((power_history[i] - power_history[i+1]) < -50)) {
702 long_delta = 888888;
703 break;
708 snprintf(power_message, POWER_MESSAGE_LEN,
709 "Chg %dm, max %dm", powermgmt_last_cycle_startstop_min,
710 charge_max_time_now);
712 * End of charge criteria (any qualify):
713 * 1) Charged a long time
714 * 2) DeltaV went negative for a short time ( & long delta static)
715 * 3) DeltaV was negative over a longer period (no disk use only)
716 * Note: short_delta and long_delta are millivolts
718 if ((powermgmt_last_cycle_startstop_min >= charge_max_time_now) ||
719 (short_delta <= -50 && long_delta < 50 ) || (long_delta < -20 &&
720 last_disk_activity > CHARGE_END_LONGD)) {
721 if (powermgmt_last_cycle_startstop_min > charge_max_time_now) {
722 DEBUGF("power: powermgmt_last_cycle_startstop_min > charge_max_time_now, "
723 "enough!\n");
725 *have charged too long and deltaV detection did not
726 *work!
728 snprintf(power_message, POWER_MESSAGE_LEN,
729 "Chg tmout %d min", charge_max_time_now);
731 * Switch to trickle charging. We skip the top-off
732 * since we've effectively done the top-off operation
733 * already since we charged for the maximum full
734 * charge time.
736 powermgmt_last_cycle_level = battery_percent;
737 powermgmt_last_cycle_startstop_min = 0;
738 charge_state = TRICKLE;
741 * set trickle charge target to a relative voltage instead
742 * of an arbitrary value - the fully charged voltage may
743 * vary according to ambient temp, battery condition etc
744 * trickle target is -0.15v from full voltage acheived
745 * topup target is -0.05v from full voltage
747 target_voltage = power_history[0] - 150;
749 } else {
750 if(short_delta <= -5) {
751 DEBUGF("power: short-term negative"
752 " delta, enough!\n");
753 snprintf(power_message, POWER_MESSAGE_LEN,
754 "end negd %d %dmin", short_delta,
755 powermgmt_last_cycle_startstop_min);
756 target_voltage = power_history[CHARGE_END_SHORTD - 1]
757 - 50;
758 } else {
759 DEBUGF("power: long-term small "
760 "positive delta, enough!\n");
761 snprintf(power_message, POWER_MESSAGE_LEN,
762 "end lowd %d %dmin", long_delta,
763 powermgmt_last_cycle_startstop_min);
764 target_voltage = power_history[CHARGE_END_LONGD - 1]
765 - 50;
768 * Switch to top-off charging.
770 powermgmt_last_cycle_level = battery_percent;
771 powermgmt_last_cycle_startstop_min = 0;
772 charge_state = TOPOFF;
776 else if (charge_state != DISCHARGING) /* top off or trickle */
779 *Time to switch from topoff to trickle?
781 if ((charge_state == TOPOFF) &&
782 (powermgmt_last_cycle_startstop_min > TOPOFF_MAX_TIME))
784 powermgmt_last_cycle_level = battery_percent;
785 powermgmt_last_cycle_startstop_min = 0;
786 charge_state = TRICKLE;
787 target_voltage = target_voltage - 100;
790 * Adjust trickle charge time (proportional and integral terms).
791 * Note: I considered setting the level higher if the USB is
792 * plugged in, but it doesn't appear to be necessary and will
793 * generate more heat [gvb].
796 pid_p = ((signed)target_voltage - (signed)battery_millivolts) / 5;
797 if((pid_p <= PID_DEADZONE) && (pid_p >= -PID_DEADZONE))
798 pid_p = 0;
800 if((unsigned) battery_millivolts < target_voltage) {
801 if(pid_i < 60) {
802 pid_i++; /* limit so it doesn't "wind up" */
804 } else {
805 if(pid_i > 0) {
806 pid_i--; /* limit so it doesn't "wind up" */
810 trickle_sec = pid_p + pid_i;
812 if(trickle_sec > 60) {
813 trickle_sec = 60;
815 if(trickle_sec < 0) {
816 trickle_sec = 0;
819 } else if (charge_state == DISCHARGING) {
820 trickle_sec = 0;
822 * The charger is enabled here only in one case: if it was
823 * turned on at boot time (power_init). Turn it off now.
825 if (charger_enabled)
826 charger_enable(false);
829 if (charger_input_state == CHARGER_UNPLUGGED) {
831 * The charger was just unplugged.
833 DEBUGF("power: charger disconnected, disabling\n");
835 charger_enable(false);
836 powermgmt_last_cycle_level = battery_percent;
837 powermgmt_last_cycle_startstop_min = 0;
838 trickle_sec = 0;
839 pid_p = 0;
840 pid_i = 0;
841 charge_state = DISCHARGING;
842 snprintf(power_message, POWER_MESSAGE_LEN, "Charger: discharge");
845 /* sleep for a minute */
846 if(trickle_sec > 0) {
847 charger_enable(true);
848 power_thread_sleep(HZ * trickle_sec);
850 if(trickle_sec < 60)
851 charger_enable(false);
852 power_thread_sleep(HZ * (60 - trickle_sec));
854 #if defined(DEBUG_FILE)
855 if(usb_inserted()) {
856 if(fd >= 0) {
857 /* It is probably too late to close the file but we can try...*/
858 close(fd);
859 fd = -1;
861 } else {
862 if(fd < 0) {
863 fd = open(DEBUG_FILE_NAME, O_WRONLY | O_APPEND | O_CREAT);
864 if(fd >= 0) {
865 snprintf(debug_message, DEBUG_MESSAGE_LEN,
866 "cycle_min, bat_millivolts, bat_percent, chgr_state"
867 " ,charge_state, pid_p, pid_i, trickle_sec\n");
868 write(fd, debug_message, strlen(debug_message));
869 wrcount = 99; /* force a flush */
872 if(fd >= 0) {
873 snprintf(debug_message, DEBUG_MESSAGE_LEN,
874 "%d, %d, %d, %d, %d, %d, %d, %d\n",
875 powermgmt_last_cycle_startstop_min, battery_millivolts,
876 battery_percent, charger_input_state, charge_state,
877 pid_p, pid_i, trickle_sec);
878 write(fd, debug_message, strlen(debug_message));
879 wrcount++;
882 #endif /* defined(DEBUG_FILE) */
884 powermgmt_last_cycle_startstop_min++;
888 * Prepare charging for poweroff
890 static inline void charging_algorithm_close(void)
892 #if defined(DEBUG_FILE)
893 if(fd >= 0) {
894 close(fd);
895 fd = -1;
897 #endif
899 #else
900 #define BATT_AVE_SAMPLES 128 /* slw filter constant for all others */
902 static inline void charging_algorithm_small_step(void)
904 #if CONFIG_CHARGING == CHARGING_MONITOR
905 switch (charger_input_state)
907 case CHARGER_UNPLUGGED:
908 case NO_CHARGER:
909 charge_state = DISCHARGING;
910 break;
911 case CHARGER_PLUGGED:
912 case CHARGER:
913 if (charging_state()) {
914 charge_state = CHARGING;
915 } else {
916 charge_state = DISCHARGING;
918 break;
920 #endif /* CONFIG_CHARGING == CHARGING_MONITOR */
923 static inline void charging_algorithm_big_step(void)
925 /* sleep for a minute */
926 power_thread_sleep(HZ * 60);
930 * Prepare charging for poweroff
932 static inline void charging_algorithm_close(void)
934 /* Nothing to do */
936 #endif /* CONFIG_CHARGING == CHARGING_CONTROL */
939 * This function is called to do the relativly long sleep waits from within the
940 * main power_thread loop while at the same time servicing any other periodic
941 * functions in the power thread which need to be called at a faster periodic
942 * rate than the slow periodic rate of the main power_thread loop.
944 * While we are waiting for the time to expire, we average the battery
945 * voltages.
947 static void power_thread_sleep(int ticks)
949 int small_ticks;
951 while (ticks > 0) {
953 #if CONFIG_CHARGING
955 * Detect charger plugged/unplugged transitions. On a plugged or
956 * unplugged event, we return immediately, run once through the main
957 * loop (including the subroutines), and end up back here where we
958 * transition to the appropriate steady state charger on/off state.
960 if(charger_inserted()
961 #ifdef HAVE_USB_POWER /* USB powered or USB inserted both provide power */
962 || usb_powered()
963 || (usb_inserted() && usb_charging_enabled())
964 #endif
966 switch(charger_input_state) {
967 case NO_CHARGER:
968 case CHARGER_UNPLUGGED:
969 charger_input_state = CHARGER_PLUGGED;
970 return;
971 case CHARGER_PLUGGED:
972 queue_broadcast(SYS_CHARGER_CONNECTED, 0);
973 last_sent_battery_level = 0;
974 charger_input_state = CHARGER;
975 break;
976 case CHARGER:
977 break;
979 } else { /* charger not inserted */
980 switch(charger_input_state) {
981 case NO_CHARGER:
982 break;
983 case CHARGER_UNPLUGGED:
984 queue_broadcast(SYS_CHARGER_DISCONNECTED, 0);
985 last_sent_battery_level = 100;
986 charger_input_state = NO_CHARGER;
987 break;
988 case CHARGER_PLUGGED:
989 case CHARGER:
990 charger_input_state = CHARGER_UNPLUGGED;
991 return;
994 #endif /* CONFIG_CHARGING */
996 small_ticks = MIN(HZ/2, ticks);
997 sleep(small_ticks);
998 ticks -= small_ticks;
1000 /* If the power off timeout expires, the main thread has failed
1001 to shut down the system, and we need to force a power off */
1002 if(shutdown_timeout) {
1003 shutdown_timeout -= small_ticks;
1004 if(shutdown_timeout <= 0)
1005 power_off();
1008 #ifdef HAVE_RTC_ALARM
1009 power_thread_rtc_process();
1010 #endif
1013 * Do a digital exponential filter. We don't sample the battery if
1014 * the disk is spinning unless we are in USB mode (the disk will most
1015 * likely always be spinning in USB mode).
1017 if (!storage_disk_is_active() || usb_inserted()) {
1018 avgbat += battery_adc_voltage() - (avgbat / BATT_AVE_SAMPLES);
1020 * battery_millivolts is the millivolt-scaled filtered battery value.
1022 battery_millivolts = avgbat / BATT_AVE_SAMPLES;
1024 /* update battery status every time an update is available */
1025 battery_status_update();
1027 else if (battery_percent < 8) {
1028 /* If battery is low, observe voltage during disk activity.
1029 * Shut down if voltage drops below shutoff level and we are not
1030 * using NiMH or Alkaline batteries.
1032 battery_millivolts = (battery_adc_voltage() +
1033 battery_millivolts + 1) / 2;
1035 /* update battery status every time an update is available */
1036 battery_status_update();
1038 #ifndef NO_LOW_BATTERY_SHUTDOWN
1039 if (!shutdown_timeout &&
1040 (battery_millivolts < battery_level_shutoff[battery_type]))
1041 sys_poweroff();
1042 else
1043 #endif
1044 avgbat += battery_millivolts - (avgbat / BATT_AVE_SAMPLES);
1047 charging_algorithm_small_step();
1051 static void power_thread(void)
1053 /* Delay reading the first battery level */
1054 #ifdef MROBE_100
1055 while(battery_adc_voltage()>4200) /* gives false readings initially */
1056 #endif
1057 sleep(HZ/100);
1059 /* initialize the voltages for the exponential filter */
1060 avgbat = battery_adc_voltage() + 15;
1062 #ifdef HAVE_DISK_STORAGE /* this adjustment is only needed for HD based */
1063 /* The battery voltage is usually a little lower directly after
1064 turning on, because the disk was used heavily. Raise it by 5% */
1065 #ifdef HAVE_CHARGING
1066 if(!charger_inserted()) /* only if charger not connected */
1067 #endif
1068 avgbat += (percent_to_volt_discharge[battery_type][6] -
1069 percent_to_volt_discharge[battery_type][5]) / 2;
1070 #endif /* HAVE_DISK_STORAGE */
1072 avgbat = avgbat * BATT_AVE_SAMPLES;
1073 battery_millivolts = avgbat / BATT_AVE_SAMPLES;
1075 #if CONFIG_CHARGING
1076 if(charger_inserted()) {
1077 battery_percent = voltage_to_percent(battery_millivolts,
1078 percent_to_volt_charge);
1079 } else
1080 #endif
1081 { battery_percent = voltage_to_percent(battery_millivolts,
1082 percent_to_volt_discharge[battery_type]);
1083 battery_percent += (battery_percent < 100);
1086 while (1)
1088 /* rotate the power history */
1089 memmove(power_history + 1, power_history,
1090 sizeof(power_history) - sizeof(power_history[0]));
1092 /* insert new value at the start, in millivolts 8-) */
1093 power_history[0] = battery_millivolts;
1095 charging_algorithm_big_step();
1097 handle_auto_poweroff();
1101 void powermgmt_init(void)
1103 /* init history to 0 */
1104 memset(power_history, 0x00, sizeof(power_history));
1105 create_thread(power_thread, power_stack, sizeof(power_stack), 0,
1106 power_thread_name IF_PRIO(, PRIORITY_SYSTEM)
1107 IF_COP(, CPU));
1110 #endif /* SIMULATOR */
1112 void sys_poweroff(void)
1114 logf("sys_poweroff()");
1115 /* If the main thread fails to shut down the system, we will force a
1116 power off after an 20 second timeout - 28 seconds if recording */
1117 if (shutdown_timeout == 0)
1119 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1120 pcf50606_reset_timeout(); /* Reset timer on first attempt only */
1121 #endif
1122 #if defined(HAVE_RECORDING) && !defined(BOOTLOADER)
1123 if (audio_status() & AUDIO_STATUS_RECORD)
1124 shutdown_timeout += HZ*8;
1125 #endif
1126 shutdown_timeout += HZ*20;
1129 queue_broadcast(SYS_POWEROFF, 0);
1132 void cancel_shutdown(void)
1134 logf("sys_cancel_shutdown()");
1136 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1137 /* TODO: Move some things to target/ tree */
1138 if (shutdown_timeout)
1139 pcf50606_reset_timeout();
1140 #endif
1142 shutdown_timeout = 0;
1145 /* Various hardware housekeeping tasks relating to shutting down the jukebox */
1146 void shutdown_hw(void)
1148 #ifndef SIMULATOR
1149 charging_algorithm_close();
1150 audio_stop();
1151 if (battery_level_safe()) { /* do not save on critical battery */
1152 #ifdef HAVE_LCD_BITMAP
1153 glyph_cache_save();
1154 #endif
1155 if(storage_disk_is_active())
1156 storage_spindown(1);
1158 while(storage_disk_is_active())
1159 sleep(HZ/10);
1161 #if CONFIG_CODEC != SWCODEC
1162 mp3_shutdown();
1163 #else
1164 audiohw_close();
1165 #endif
1167 /* If HD is still active we try to wait for spindown, otherwise the
1168 shutdown_timeout in power_thread_sleep will force a power off */
1169 while(storage_disk_is_active())
1170 sleep(HZ/10);
1171 #ifndef IAUDIO_X5
1172 lcd_set_contrast(0);
1173 #endif /* IAUDIO_X5 */
1174 #ifdef HAVE_REMOTE_LCD
1175 lcd_remote_set_contrast(0);
1176 #endif
1178 #ifdef HAVE_LCD_SHUTDOWN
1179 lcd_shutdown();
1180 #endif
1182 /* Small delay to make sure all HW gets time to flush. Especially
1183 eeprom chips are quite slow and might be still writing the last
1184 byte. */
1185 sleep(HZ/4);
1186 power_off();
1187 #endif /* #ifndef SIMULATOR */
1190 /* Send system battery level update events on reaching certain significant
1191 levels. This must be called after battery_percent has been updated. */
1192 static void send_battery_level_event(void)
1194 static const int levels[] = { 5, 15, 30, 50, 0 };
1195 const int *level = levels;
1196 while (*level)
1198 if (battery_percent <= *level && last_sent_battery_level > *level)
1200 last_sent_battery_level = *level;
1201 queue_broadcast(SYS_BATTERY_UPDATE, last_sent_battery_level);
1202 break;
1204 level++;