1 /***************************************************************************
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
10 * Copyright (C) 2002 by Heikki Hannikainen, Uwe Freese
11 * Revisions copyright (C) 2005 by Gerald Van Baren
13 * This program is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU General Public License
15 * as published by the Free Software Foundation; either version 2
16 * of the License, or (at your option) any later version.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ****************************************************************************/
36 #include "mp3_playback.h"
38 #include "powermgmt.h"
39 #include "backlight.h"
46 #ifdef HAVE_LCD_BITMAP
49 #if defined(HAVE_RECORDING) && (CONFIG_CODEC == SWCODEC)
50 #include "pcm_record.h"
53 #include "lcd-remote.h"
58 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
60 #include "lcd-remote-target.h"
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.
68 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
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;
80 static int shutdown_timeout
= 0;
81 #if CONFIG_CHARGING >= CHARGING_MONITOR
82 charge_state_type charge_state
; /* charging mode */
85 static void send_battery_level_event(void);
86 static int last_sent_battery_level
= 100;
89 charger_input_state_type charger_input_state IDATA_ATTR
;
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;
109 if (last_change
< now
)
113 /* change the values: */
116 if (battery_millivolts
>= BATT_MAXMVOLT
)
118 /* Pretend the charger was disconnected */
120 queue_broadcast(SYS_CHARGER_DISCONNECTED
, 0);
121 last_sent_battery_level
= 100;
126 if (battery_millivolts
<= BATT_MINMVOLT
)
128 /* Pretend the charger was connected */
130 queue_broadcast(SYS_CHARGER_CONNECTED
, 0);
131 last_sent_battery_level
= 0;
135 battery_millivolts
+= (BATT_MAXMVOLT
- BATT_MINMVOLT
) / 50;
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();
151 *voltage
= battery_millivolts
;
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
)
185 void set_battery_capacity(int capacity
)
190 #if BATTERY_TYPES_COUNT > 1
191 void set_battery_type(int type
)
197 void reset_poweroff_timer(void)
201 #ifdef HAVE_ACCESSORY_SUPPLY
202 void accessory_supply_set(bool enable
)
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;
226 #define battery_type 0
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();
252 *voltage
= millivolts
;
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
) {
268 battery_status_update(); /* recalculate the battery status */
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
)
314 sleeptimer_active
= true;
315 sleeptimer_endtick
= current_tick
+ seconds
* HZ
;
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
;
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])
337 if (voltage
>= table
[10])
340 /* search nearest value */
342 while ((i
< 10) && (table
[i
+1] < voltage
))
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
)
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 */
371 /* always use the discharge table */
372 level
= voltage_to_percent(battery_millivolts
,
373 percent_to_volt_discharge
[battery_type
]);
374 #endif /* CONFIG_CHARGING ... */
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());
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;
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();
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
;
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
) {
448 #if CONFIG_TUNER && !defined(BOOTLOADER)
449 (!(get_radio_status() & FMRADIO_PLAYING
)) &&
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
))
464 /* Handle sleeptimer */
465 if(sleeptimer_active
&& !usb_inserted())
467 if(TIME_AFTER(current_tick
, sleeptimer_endtick
))
470 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
471 if((charger_input_state
== CHARGER
) ||
472 (charger_input_state
== CHARGER_PLUGGED
))
474 DEBUGF("Sleep timer timeout. Stopping...\n");
476 backlight_off(); /* Nighty, nighty... */
481 DEBUGF("Sleep timer timeout. Shutting off...\n");
490 * Estimate how much current we are drawing just to run.
492 static int runcurrent(void)
496 #if MEM == 8 && !defined(HAVE_MMC)
497 /* assuming 192 kbps, the running time is 22% longer with 8MB */
498 current
= (CURRENT_NORMAL
*100/122);
500 current
= CURRENT_NORMAL
;
501 #endif /* MEM == 8 */
504 #if defined(HAVE_USB_POWER)
505 #if (CURRENT_USB < CURRENT_NORMAL)
513 current
= CURRENT_USB
;
516 #if defined(HAVE_BACKLIGHT) && !defined(BOOTLOADER)
517 if (backlight_get_current_timeout() == 0) /* LED always on */
518 current
+= CURRENT_BACKLIGHT
;
521 #if defined(HAVE_RECORDING) && defined(CURRENT_RECORD)
522 if (audio_status() & AUDIO_STATUS_RECORD
)
523 current
+= CURRENT_RECORD
;
526 #ifdef HAVE_SPDIF_POWER
528 current
+= CURRENT_SPDIF_OUT
;
531 #ifdef HAVE_REMOTE_LCD
533 current
+= CURRENT_REMOTE
;
540 /* Check to see whether or not we've received an alarm in the last second */
541 #ifdef HAVE_RTC_ALARM
542 static void power_thread_rtc_process(void)
544 if (rtc_check_alarm_flag()) {
545 rtc_enable_alarm(false);
551 * This power thread maintains a history of battery voltage
552 * and implements a charging algorithm.
554 #if CONFIG_CHARGING == CHARGING_CONTROL
555 #define BATT_AVE_SAMPLES 32 /* filter constant / @ 2Hz sample rate */
558 * For a complete description of the charging algorithm read
559 * docs/CHARGING_ALGORITHM.
561 int long_delta
; /* long term delta battery voltage */
562 int short_delta
; /* short term delta battery voltage */
563 bool disk_activity_last_cycle
= false; /* flag set to aid charger time
565 char power_message
[POWER_MESSAGE_LEN
] = ""; /* message that's shown in
567 /* percentage at which charging
569 int powermgmt_last_cycle_startstop_min
= 0; /* how many minutes ago was the
572 int powermgmt_last_cycle_level
= 0; /* which level had the
573 batteries at this time? */
574 int trickle_sec
= 0; /* how many seconds should the
575 charger be enabled per
578 int pid_p
= 0; /* PID proportional term */
579 int pid_i
= 0; /* PID integral term */
581 static inline void charging_algorithm_small_step(void)
583 if (ata_disk_is_active()) {
584 /* flag hdd use for charging calculation */
585 disk_activity_last_cycle
= true;
588 #if defined(DEBUG_FILE)
590 * If we have a lot of pending writes or if the disk is spining,
591 * fsync the debug log file.
593 if((wrcount
> 10) || ((wrcount
> 0) && ata_disk_is_active())) {
597 #endif /* defined(DEBUG_FILE) */
600 static inline void charging_algorithm_big_step(void)
602 static unsigned int target_voltage
= TRICKLE_VOLTAGE
; /* desired topoff/trickle
604 static int charge_max_time_idle
= 0; /* max. charging duration, calculated at
605 * beginning of charging */
606 static int charge_max_time_now
= 0; /* max. charging duration including
608 static int minutes_disk_activity
= 0; /* count minutes of hdd use during
610 static int last_disk_activity
= CHARGE_END_LONGD
+ 1; /* last hdd use x mins ago */
613 if (charger_input_state
== CHARGER_PLUGGED
) {
616 snprintf(power_message
, POWER_MESSAGE_LEN
, "Charger plugged in");
618 * The charger was just plugged in. If the battery level is
619 * nearly charged, just trickle. If the battery is low, start
620 * a full charge cycle. If the battery level is in between,
621 * top-off and then trickle.
623 if(battery_percent
> START_TOPOFF_CHG
) {
624 powermgmt_last_cycle_level
= battery_percent
;
625 powermgmt_last_cycle_startstop_min
= 0;
626 if(battery_percent
>= START_TRICKLE_CHG
) {
627 charge_state
= TRICKLE
;
628 target_voltage
= TRICKLE_VOLTAGE
;
630 charge_state
= TOPOFF
;
631 target_voltage
= TOPOFF_VOLTAGE
;
635 * Start the charger full strength
637 i
= CHARGE_MAX_TIME_1500
* battery_capacity
/ 1500;
638 charge_max_time_idle
=
639 i
* (100 + 35 - battery_percent
) / 100;
640 if (charge_max_time_idle
> i
) {
641 charge_max_time_idle
= i
;
643 charge_max_time_now
= charge_max_time_idle
;
645 snprintf(power_message
, POWER_MESSAGE_LEN
,
646 "ChgAt %d%% max %dm", battery_level(),
647 charge_max_time_now
);
649 /* enable the charger after the max time calc is done,
650 because battery_level depends on if the charger is
652 DEBUGF("power: charger inserted and battery"
653 " not full, charging\n");
654 powermgmt_last_cycle_level
= battery_percent
;
655 powermgmt_last_cycle_startstop_min
= 0;
657 long_delta
= short_delta
= 999999;
658 charge_state
= CHARGING
;
662 if (charge_state
== CHARGING
) {
663 /* alter charge time max length with extra disk use */
664 if (disk_activity_last_cycle
) {
665 minutes_disk_activity
++;
666 charge_max_time_now
= charge_max_time_idle
+
667 (minutes_disk_activity
* 2 / 5);
668 disk_activity_last_cycle
= false;
669 last_disk_activity
= 0;
671 last_disk_activity
++;
674 * Check the delta voltage over the last X minutes so we can do
675 * our end-of-charge logic based on the battery level change.
676 *(no longer use minimum time as logic for charge end has 50
677 * minutes minimum charge built in)
679 if (powermgmt_last_cycle_startstop_min
> CHARGE_END_SHORTD
) {
680 short_delta
= power_history
[0] -
681 power_history
[CHARGE_END_SHORTD
- 1];
684 if (powermgmt_last_cycle_startstop_min
> CHARGE_END_LONGD
) {
686 * Scan the history: the points where measurement is taken need to
687 * be fairly static. (check prior to short delta 'area')
688 * (also only check first and last 10 cycles - delta in middle OK)
690 long_delta
= power_history
[0] -
691 power_history
[CHARGE_END_LONGD
- 1];
693 for(i
= CHARGE_END_SHORTD
; i
< CHARGE_END_SHORTD
+ 10; i
++) {
694 if(((power_history
[i
] - power_history
[i
+1]) > 50) ||
695 ((power_history
[i
] - power_history
[i
+1]) < -50)) {
700 for(i
= CHARGE_END_LONGD
- 11; i
< CHARGE_END_LONGD
- 1 ; i
++) {
701 if(((power_history
[i
] - power_history
[i
+1]) > 50) ||
702 ((power_history
[i
] - power_history
[i
+1]) < -50)) {
709 snprintf(power_message
, POWER_MESSAGE_LEN
,
710 "Chg %dm, max %dm", powermgmt_last_cycle_startstop_min
,
711 charge_max_time_now
);
713 * End of charge criteria (any qualify):
714 * 1) Charged a long time
715 * 2) DeltaV went negative for a short time ( & long delta static)
716 * 3) DeltaV was negative over a longer period (no disk use only)
717 * Note: short_delta and long_delta are millivolts
719 if ((powermgmt_last_cycle_startstop_min
>= charge_max_time_now
) ||
720 (short_delta
<= -50 && long_delta
< 50 ) || (long_delta
< -20 &&
721 last_disk_activity
> CHARGE_END_LONGD
)) {
722 if (powermgmt_last_cycle_startstop_min
> charge_max_time_now
) {
723 DEBUGF("power: powermgmt_last_cycle_startstop_min > charge_max_time_now, "
726 *have charged too long and deltaV detection did not
729 snprintf(power_message
, POWER_MESSAGE_LEN
,
730 "Chg tmout %d min", charge_max_time_now
);
732 * Switch to trickle charging. We skip the top-off
733 * since we've effectively done the top-off operation
734 * already since we charged for the maximum full
737 powermgmt_last_cycle_level
= battery_percent
;
738 powermgmt_last_cycle_startstop_min
= 0;
739 charge_state
= TRICKLE
;
742 * set trickle charge target to a relative voltage instead
743 * of an arbitrary value - the fully charged voltage may
744 * vary according to ambient temp, battery condition etc
745 * trickle target is -0.15v from full voltage acheived
746 * topup target is -0.05v from full voltage
748 target_voltage
= power_history
[0] - 150;
751 if(short_delta
<= -5) {
752 DEBUGF("power: short-term negative"
753 " delta, enough!\n");
754 snprintf(power_message
, POWER_MESSAGE_LEN
,
755 "end negd %d %dmin", short_delta
,
756 powermgmt_last_cycle_startstop_min
);
757 target_voltage
= power_history
[CHARGE_END_SHORTD
- 1]
760 DEBUGF("power: long-term small "
761 "positive delta, enough!\n");
762 snprintf(power_message
, POWER_MESSAGE_LEN
,
763 "end lowd %d %dmin", long_delta
,
764 powermgmt_last_cycle_startstop_min
);
765 target_voltage
= power_history
[CHARGE_END_LONGD
- 1]
769 * Switch to top-off charging.
771 powermgmt_last_cycle_level
= battery_percent
;
772 powermgmt_last_cycle_startstop_min
= 0;
773 charge_state
= TOPOFF
;
777 else if (charge_state
!= DISCHARGING
) /* top off or trickle */
780 *Time to switch from topoff to trickle?
782 if ((charge_state
== TOPOFF
) &&
783 (powermgmt_last_cycle_startstop_min
> TOPOFF_MAX_TIME
))
785 powermgmt_last_cycle_level
= battery_percent
;
786 powermgmt_last_cycle_startstop_min
= 0;
787 charge_state
= TRICKLE
;
788 target_voltage
= target_voltage
- 100;
791 * Adjust trickle charge time (proportional and integral terms).
792 * Note: I considered setting the level higher if the USB is
793 * plugged in, but it doesn't appear to be necessary and will
794 * generate more heat [gvb].
797 pid_p
= ((signed)target_voltage
- (signed)battery_millivolts
) / 5;
798 if((pid_p
<= PID_DEADZONE
) && (pid_p
>= -PID_DEADZONE
))
801 if((unsigned) battery_millivolts
< target_voltage
) {
803 pid_i
++; /* limit so it doesn't "wind up" */
807 pid_i
--; /* limit so it doesn't "wind up" */
811 trickle_sec
= pid_p
+ pid_i
;
813 if(trickle_sec
> 60) {
816 if(trickle_sec
< 0) {
820 } else if (charge_state
== DISCHARGING
) {
823 * The charger is enabled here only in one case: if it was
824 * turned on at boot time (power_init). Turn it off now.
827 charger_enable(false);
830 if (charger_input_state
== CHARGER_UNPLUGGED
) {
832 * The charger was just unplugged.
834 DEBUGF("power: charger disconnected, disabling\n");
836 charger_enable(false);
837 powermgmt_last_cycle_level
= battery_percent
;
838 powermgmt_last_cycle_startstop_min
= 0;
842 charge_state
= DISCHARGING
;
843 snprintf(power_message
, POWER_MESSAGE_LEN
, "Charger: discharge");
846 /* sleep for a minute */
847 if(trickle_sec
> 0) {
848 charger_enable(true);
849 power_thread_sleep(HZ
* trickle_sec
);
852 charger_enable(false);
853 power_thread_sleep(HZ
* (60 - trickle_sec
));
855 #if defined(DEBUG_FILE)
858 /* It is probably too late to close the file but we can try...*/
864 fd
= open(DEBUG_FILE_NAME
, O_WRONLY
| O_APPEND
| O_CREAT
);
866 snprintf(debug_message
, DEBUG_MESSAGE_LEN
,
867 "cycle_min, bat_millivolts, bat_percent, chgr_state"
868 " ,charge_state, pid_p, pid_i, trickle_sec\n");
869 write(fd
, debug_message
, strlen(debug_message
));
870 wrcount
= 99; /* force a flush */
874 snprintf(debug_message
, DEBUG_MESSAGE_LEN
,
875 "%d, %d, %d, %d, %d, %d, %d, %d\n",
876 powermgmt_last_cycle_startstop_min
, battery_millivolts
,
877 battery_percent
, charger_input_state
, charge_state
,
878 pid_p
, pid_i
, trickle_sec
);
879 write(fd
, debug_message
, strlen(debug_message
));
883 #endif /* defined(DEBUG_FILE) */
885 powermgmt_last_cycle_startstop_min
++;
889 * Prepare charging for poweroff
891 static inline void charging_algorithm_close(void)
893 #if defined(DEBUG_FILE)
901 #define BATT_AVE_SAMPLES 128 /* slw filter constant for all others */
903 static inline void charging_algorithm_small_step(void)
905 #if CONFIG_CHARGING == CHARGING_MONITOR
906 switch (charger_input_state
)
908 case CHARGER_UNPLUGGED
:
910 charge_state
= DISCHARGING
;
912 case CHARGER_PLUGGED
:
914 if (charging_state()) {
915 charge_state
= CHARGING
;
917 charge_state
= DISCHARGING
;
921 #endif /* CONFIG_CHARGING == CHARGING_MONITOR */
924 static inline void charging_algorithm_big_step(void)
926 /* sleep for a minute */
927 power_thread_sleep(HZ
* 60);
931 * Prepare charging for poweroff
933 static inline void charging_algorithm_close(void)
937 #endif /* CONFIG_CHARGING == CHARGING_CONTROL */
940 * This function is called to do the relativly long sleep waits from within the
941 * main power_thread loop while at the same time servicing any other periodic
942 * functions in the power thread which need to be called at a faster periodic
943 * rate than the slow periodic rate of the main power_thread loop.
945 * While we are waiting for the time to expire, we average the battery
948 static void power_thread_sleep(int ticks
)
956 * Detect charger plugged/unplugged transitions. On a plugged or
957 * unplugged event, we return immediately, run once through the main
958 * loop (including the subroutines), and end up back here where we
959 * transition to the appropriate steady state charger on/off state.
961 if(charger_inserted()
962 #ifdef HAVE_USB_POWER /* USB powered or USB inserted both provide power */
964 || (usb_inserted() && usb_charging_enabled())
967 switch(charger_input_state
) {
969 case CHARGER_UNPLUGGED
:
970 charger_input_state
= CHARGER_PLUGGED
;
972 case CHARGER_PLUGGED
:
973 queue_broadcast(SYS_CHARGER_CONNECTED
, 0);
974 last_sent_battery_level
= 0;
975 charger_input_state
= CHARGER
;
980 } else { /* charger not inserted */
981 switch(charger_input_state
) {
984 case CHARGER_UNPLUGGED
:
985 queue_broadcast(SYS_CHARGER_DISCONNECTED
, 0);
986 last_sent_battery_level
= 100;
987 charger_input_state
= NO_CHARGER
;
989 case CHARGER_PLUGGED
:
991 charger_input_state
= CHARGER_UNPLUGGED
;
995 #endif /* CONFIG_CHARGING */
997 small_ticks
= MIN(HZ
/2, ticks
);
999 ticks
-= small_ticks
;
1001 /* If the power off timeout expires, the main thread has failed
1002 to shut down the system, and we need to force a power off */
1003 if(shutdown_timeout
) {
1004 shutdown_timeout
-= small_ticks
;
1005 if(shutdown_timeout
<= 0)
1009 #ifdef HAVE_RTC_ALARM
1010 power_thread_rtc_process();
1014 * Do a digital exponential filter. We don't sample the battery if
1015 * the disk is spinning unless we are in USB mode (the disk will most
1016 * likely always be spinning in USB mode).
1018 if (!ata_disk_is_active() || usb_inserted()) {
1019 avgbat
+= battery_adc_voltage() - (avgbat
/ BATT_AVE_SAMPLES
);
1021 * battery_millivolts is the millivolt-scaled filtered battery value.
1023 battery_millivolts
= avgbat
/ BATT_AVE_SAMPLES
;
1025 /* update battery status every time an update is available */
1026 battery_status_update();
1028 else if (battery_percent
< 8) {
1029 /* If battery is low, observe voltage during disk activity.
1030 * Shut down if voltage drops below shutoff level and we are not
1031 * using NiMH or Alkaline batteries.
1033 battery_millivolts
= (battery_adc_voltage() +
1034 battery_millivolts
+ 1) / 2;
1036 /* update battery status every time an update is available */
1037 battery_status_update();
1039 #ifndef NO_LOW_BATTERY_SHUTDOWN
1040 if (!shutdown_timeout
&&
1041 (battery_millivolts
< battery_level_shutoff
[battery_type
]))
1045 avgbat
+= battery_millivolts
- (avgbat
/ BATT_AVE_SAMPLES
);
1048 charging_algorithm_small_step();
1052 static void power_thread(void)
1054 /* Delay reading the first battery level */
1056 while(battery_adc_voltage()>4200) /* gives false readings initially */
1060 /* initialize the voltages for the exponential filter */
1061 avgbat
= battery_adc_voltage() + 15;
1063 #ifndef HAVE_MMC /* this adjustment is only needed for HD based */
1064 /* The battery voltage is usually a little lower directly after
1065 turning on, because the disk was used heavily. Raise it by 5% */
1066 #ifdef HAVE_CHARGING
1067 if(!charger_inserted()) /* only if charger not connected */
1069 avgbat
+= (percent_to_volt_discharge
[battery_type
][6] -
1070 percent_to_volt_discharge
[battery_type
][5]) / 2;
1071 #endif /* not HAVE_MMC */
1073 avgbat
= avgbat
* BATT_AVE_SAMPLES
;
1074 battery_millivolts
= avgbat
/ BATT_AVE_SAMPLES
;
1077 if(charger_inserted()) {
1078 battery_percent
= voltage_to_percent(battery_millivolts
,
1079 percent_to_volt_charge
);
1082 { battery_percent
= voltage_to_percent(battery_millivolts
,
1083 percent_to_volt_discharge
[battery_type
]);
1084 battery_percent
+= (battery_percent
< 100);
1089 /* rotate the power history */
1090 memmove(power_history
+ 1, power_history
,
1091 sizeof(power_history
) - sizeof(power_history
[0]));
1093 /* insert new value at the start, in millivolts 8-) */
1094 power_history
[0] = battery_millivolts
;
1096 charging_algorithm_big_step();
1098 handle_auto_poweroff();
1102 void powermgmt_init(void)
1104 /* init history to 0 */
1105 memset(power_history
, 0x00, sizeof(power_history
));
1106 create_thread(power_thread
, power_stack
, sizeof(power_stack
), 0,
1107 power_thread_name
IF_PRIO(, PRIORITY_SYSTEM
)
1111 #endif /* SIMULATOR */
1113 void sys_poweroff(void)
1115 logf("sys_poweroff()");
1116 /* If the main thread fails to shut down the system, we will force a
1117 power off after an 20 second timeout - 28 seconds if recording */
1118 if (shutdown_timeout
== 0)
1120 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1121 pcf50606_reset_timeout(); /* Reset timer on first attempt only */
1123 #ifdef HAVE_RECORDING
1124 if (audio_status() & AUDIO_STATUS_RECORD
)
1125 shutdown_timeout
+= HZ
*8;
1127 shutdown_timeout
+= HZ
*20;
1130 queue_broadcast(SYS_POWEROFF
, 0);
1133 void cancel_shutdown(void)
1135 logf("sys_cancel_shutdown()");
1137 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1138 /* TODO: Move some things to target/ tree */
1139 if (shutdown_timeout
)
1140 pcf50606_reset_timeout();
1143 shutdown_timeout
= 0;
1146 /* Various hardware housekeeping tasks relating to shutting down the jukebox */
1147 void shutdown_hw(void)
1150 charging_algorithm_close();
1152 if (battery_level_safe()) { /* do not save on critical battery */
1153 #ifdef HAVE_LCD_BITMAP
1156 if(ata_disk_is_active())
1159 while(ata_disk_is_active())
1162 #if CONFIG_CODEC != SWCODEC
1168 /* If HD is still active we try to wait for spindown, otherwise the
1169 shutdown_timeout in power_thread_sleep will force a power off */
1170 while(ata_disk_is_active())
1173 lcd_set_contrast(0);
1174 #endif /* IAUDIO_X5 */
1175 #ifdef HAVE_REMOTE_LCD
1176 lcd_remote_set_contrast(0);
1179 #ifdef HAVE_LCD_SHUTDOWN
1183 /* Small delay to make sure all HW gets time to flush. Especially
1184 eeprom chips are quite slow and might be still writing the last
1188 #endif /* #ifndef SIMULATOR */
1191 /* Send system battery level update events on reaching certain significant
1192 levels. This must be called after battery_percent has been updated. */
1193 static void send_battery_level_event(void)
1195 static const int levels
[] = { 5, 15, 30, 50, 0 };
1196 const int *level
= levels
;
1199 if (battery_percent
<= *level
&& last_sent_battery_level
> *level
)
1201 last_sent_battery_level
= *level
;
1202 queue_broadcast(SYS_BATTERY_UPDATE
, last_sent_battery_level
);