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
50 #include "lcd-remote.h"
55 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
57 #include "lcd-remote-target.h"
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.
65 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
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;
77 static int shutdown_timeout
= 0;
78 #if CONFIG_CHARGING >= CHARGING_MONITOR
79 charge_state_type charge_state
; /* charging mode */
82 static void send_battery_level_event(void);
83 static int last_sent_battery_level
= 100;
86 charger_input_state_type charger_input_state IDATA_ATTR
;
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;
106 if (last_change
< now
)
110 /* change the values: */
113 if (battery_millivolts
>= BATT_MAXMVOLT
)
115 /* Pretend the charger was disconnected */
117 queue_broadcast(SYS_CHARGER_DISCONNECTED
, 0);
118 last_sent_battery_level
= 100;
123 if (battery_millivolts
<= BATT_MINMVOLT
)
125 /* Pretend the charger was connected */
127 queue_broadcast(SYS_CHARGER_CONNECTED
, 0);
128 last_sent_battery_level
= 0;
132 battery_millivolts
+= (BATT_MAXMVOLT
- BATT_MINMVOLT
) / 50;
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();
148 *voltage
= battery_millivolts
;
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
)
182 void set_battery_capacity(int capacity
)
187 #if BATTERY_TYPES_COUNT > 1
188 void set_battery_type(int type
)
194 void reset_poweroff_timer(void)
198 #ifdef HAVE_ACCESSORY_SUPPLY
199 void accessory_supply_set(bool enable
)
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;
223 #define battery_type 0
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();
249 *voltage
= millivolts
;
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
) {
265 battery_status_update(); /* recalculate the battery status */
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
)
311 sleeptimer_active
= true;
312 sleeptimer_endtick
= current_tick
+ seconds
* HZ
;
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
;
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])
334 if (voltage
>= table
[10])
337 /* search nearest value */
339 while ((i
< 10) && (table
[i
+1] < voltage
))
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
)
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 */
368 /* always use the discharge table */
369 level
= voltage_to_percent(battery_millivolts
,
370 percent_to_volt_discharge
[battery_type
]);
371 #endif /* CONFIG_CHARGING ... */
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());
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;
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();
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
;
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
) {
445 #if CONFIG_TUNER && !defined(BOOTLOADER)
446 (!(get_radio_status() & FMRADIO_PLAYING
)) &&
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
, last_disk_activity
+ timeout
))
461 /* Handle sleeptimer */
462 if(sleeptimer_active
)
464 if(TIME_AFTER(current_tick
, sleeptimer_endtick
))
468 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
469 || ((charger_input_state
== CHARGER
) ||
470 (charger_input_state
== CHARGER_PLUGGED
))
474 DEBUGF("Sleep timer timeout. Stopping...\n");
476 backlight_off(); /* Nighty, nighty... */
480 DEBUGF("Sleep timer timeout. Shutting off...\n");
489 * Estimate how much current we are drawing just to run.
491 static int runcurrent(void)
495 #if MEM == 8 && !defined(HAVE_MMC)
496 /* assuming 192 kbps, the running time is 22% longer with 8MB */
497 current
= (CURRENT_NORMAL
*100/122);
499 current
= CURRENT_NORMAL
;
500 #endif /* MEM == 8 */
503 #if defined(HAVE_USB_POWER)
504 #if (CURRENT_USB < CURRENT_NORMAL)
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
;
520 #if defined(HAVE_RECORDING) && defined(CURRENT_RECORD)
521 if (audio_status() & AUDIO_STATUS_RECORD
)
522 current
+= CURRENT_RECORD
;
525 #ifdef HAVE_SPDIF_POWER
527 current
+= CURRENT_SPDIF_OUT
;
530 #ifdef HAVE_REMOTE_LCD
532 current
+= CURRENT_REMOTE
;
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);
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
564 char power_message
[POWER_MESSAGE_LEN
] = ""; /* message that's shown in
566 /* percentage at which charging
568 int powermgmt_last_cycle_startstop_min
= 0; /* how many minutes ago was the
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
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 (ata_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) && ata_disk_is_active())) {
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
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
607 static int minutes_disk_activity
= 0; /* count minutes of hdd use during
609 static int last_disk_activity
= CHARGE_END_LONGD
+ 1; /* last hdd use x mins ago */
612 if (charger_input_state
== CHARGER_PLUGGED
) {
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
;
629 charge_state
= TOPOFF
;
630 target_voltage
= TOPOFF_VOLTAGE
;
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
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;
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;
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)) {
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)) {
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, "
725 *have charged too long and deltaV detection did not
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
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;
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]
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]
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
))
800 if((unsigned) battery_millivolts
< target_voltage
) {
802 pid_i
++; /* limit so it doesn't "wind up" */
806 pid_i
--; /* limit so it doesn't "wind up" */
810 trickle_sec
= pid_p
+ pid_i
;
812 if(trickle_sec
> 60) {
815 if(trickle_sec
< 0) {
819 } else if (charge_state
== DISCHARGING
) {
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.
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;
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
);
851 charger_enable(false);
852 power_thread_sleep(HZ
* (60 - trickle_sec
));
854 #if defined(DEBUG_FILE)
857 /* It is probably too late to close the file but we can try...*/
863 fd
= open(DEBUG_FILE_NAME
, O_WRONLY
| O_APPEND
| O_CREAT
);
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 */
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
));
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)
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
:
909 charge_state
= DISCHARGING
;
911 case CHARGER_PLUGGED
:
913 if (charging_state()) {
914 charge_state
= CHARGING
;
916 charge_state
= DISCHARGING
;
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)
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
947 static void power_thread_sleep(int ticks
)
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 */
963 || (usb_inserted() && usb_charging_enabled())
966 switch(charger_input_state
) {
968 case CHARGER_UNPLUGGED
:
969 charger_input_state
= CHARGER_PLUGGED
;
971 case CHARGER_PLUGGED
:
972 queue_broadcast(SYS_CHARGER_CONNECTED
, 0);
973 last_sent_battery_level
= 0;
974 charger_input_state
= CHARGER
;
979 } else { /* charger not inserted */
980 switch(charger_input_state
) {
983 case CHARGER_UNPLUGGED
:
984 queue_broadcast(SYS_CHARGER_DISCONNECTED
, 0);
985 last_sent_battery_level
= 100;
986 charger_input_state
= NO_CHARGER
;
988 case CHARGER_PLUGGED
:
990 charger_input_state
= CHARGER_UNPLUGGED
;
994 #endif /* CONFIG_CHARGING */
996 small_ticks
= MIN(HZ
/2, 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)
1008 #ifdef HAVE_RTC_ALARM
1009 power_thread_rtc_process();
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 (!ata_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
]))
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 */
1055 while(battery_adc_voltage()>4200) /* gives false readings initially */
1059 /* initialize the voltages for the exponential filter */
1060 avgbat
= battery_adc_voltage() + 15;
1062 #ifndef HAVE_MMC /* 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 */
1068 avgbat
+= (percent_to_volt_discharge
[battery_type
][6] -
1069 percent_to_volt_discharge
[battery_type
][5]) / 2;
1070 #endif /* not HAVE_MMC */
1072 avgbat
= avgbat
* BATT_AVE_SAMPLES
;
1073 battery_millivolts
= avgbat
/ BATT_AVE_SAMPLES
;
1076 if(charger_inserted()) {
1077 battery_percent
= voltage_to_percent(battery_millivolts
,
1078 percent_to_volt_charge
);
1081 { battery_percent
= voltage_to_percent(battery_millivolts
,
1082 percent_to_volt_discharge
[battery_type
]);
1083 battery_percent
+= (battery_percent
< 100);
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
)
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 */
1122 #if defined(HAVE_RECORDING) && !defined(BOOTLOADER)
1123 if (audio_status() & AUDIO_STATUS_RECORD
)
1124 shutdown_timeout
+= HZ
*8;
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();
1142 shutdown_timeout
= 0;
1145 /* Various hardware housekeeping tasks relating to shutting down the jukebox */
1146 void shutdown_hw(void)
1149 charging_algorithm_close();
1151 if (battery_level_safe()) { /* do not save on critical battery */
1152 #ifdef HAVE_LCD_BITMAP
1155 if(ata_disk_is_active())
1158 while(ata_disk_is_active())
1161 #if CONFIG_CODEC != SWCODEC
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(ata_disk_is_active())
1172 lcd_set_contrast(0);
1173 #endif /* IAUDIO_X5 */
1174 #ifdef HAVE_REMOTE_LCD
1175 lcd_remote_set_contrast(0);
1178 #ifdef HAVE_LCD_SHUTDOWN
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
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
;
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
);