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 * 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 ****************************************************************************/
34 #include "mp3_playback.h"
36 #include "powermgmt.h"
37 #include "backlight.h"
44 #ifdef HAVE_LCD_BITMAP
47 #if defined(HAVE_RECORDING) && (CONFIG_CODEC == SWCODEC)
48 #include "pcm_record.h"
51 #include "lcd-remote.h"
56 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
58 #include "lcd-remote-target.h"
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.
66 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
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;
78 static int shutdown_timeout
= 0;
79 #if CONFIG_CHARGING >= CHARGING_MONITOR
80 charge_state_type charge_state
; /* charging mode */
83 static void send_battery_level_event(void);
84 static int last_sent_battery_level
= 100;
87 charger_input_state_type charger_input_state IDATA_ATTR
;
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;
107 if (last_change
< now
)
111 /* change the values: */
114 if (battery_millivolts
>= BATT_MAXMVOLT
)
116 /* Pretend the charger was disconnected */
118 queue_broadcast(SYS_CHARGER_DISCONNECTED
, 0);
119 last_sent_battery_level
= 100;
124 if (battery_millivolts
<= BATT_MINMVOLT
)
126 /* Pretend the charger was connected */
128 queue_broadcast(SYS_CHARGER_CONNECTED
, 0);
129 last_sent_battery_level
= 0;
133 battery_millivolts
+= (BATT_MAXMVOLT
- BATT_MINMVOLT
) / 50;
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();
149 *voltage
= battery_millivolts
;
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
)
183 void set_battery_capacity(int capacity
)
188 #if BATTERY_TYPES_COUNT > 1
189 void set_battery_type(int type
)
195 void reset_poweroff_timer(void)
199 #ifdef HAVE_ACCESSORY_SUPPLY
200 void accessory_supply_set(bool enable
)
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;
224 #define battery_type 0
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();
250 *voltage
= millivolts
;
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
) {
266 battery_status_update(); /* recalculate the battery status */
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
)
312 sleeptimer_active
= true;
313 sleeptimer_endtick
= current_tick
+ seconds
* HZ
;
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
;
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])
335 if (voltage
>= table
[10])
338 /* search nearest value */
340 while ((i
< 10) && (table
[i
+1] < voltage
))
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
)
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 */
369 /* always use the discharge table */
370 level
= voltage_to_percent(battery_millivolts
,
371 percent_to_volt_discharge
[battery_type
]);
372 #endif /* CONFIG_CHARGING ... */
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());
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;
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();
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
;
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
) {
446 #if CONFIG_TUNER && !defined(BOOTLOADER)
447 (!(get_radio_status() & FMRADIO_PLAYING
)) &&
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
))
462 /* Handle sleeptimer */
463 if(sleeptimer_active
&& !usb_inserted())
465 if(TIME_AFTER(current_tick
, sleeptimer_endtick
))
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");
474 backlight_off(); /* Nighty, nighty... */
479 DEBUGF("Sleep timer timeout. Shutting off...\n");
488 * Estimate how much current we are drawing just to run.
490 static int runcurrent(void)
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);
498 current
= CURRENT_NORMAL
;
499 #endif /* MEM == 8 */
502 #if defined(HAVE_USB_POWER)
503 #if (CURRENT_USB < CURRENT_NORMAL)
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
;
519 #if defined(HAVE_RECORDING) && defined(CURRENT_RECORD)
520 if (audio_status() & AUDIO_STATUS_RECORD
)
521 current
+= CURRENT_RECORD
;
524 #ifdef HAVE_SPDIF_POWER
526 current
+= CURRENT_SPDIF_OUT
;
529 #ifdef HAVE_REMOTE_LCD
531 current
+= CURRENT_REMOTE
;
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);
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
563 char power_message
[POWER_MESSAGE_LEN
] = ""; /* message that's shown in
565 /* percentage at which charging
567 int powermgmt_last_cycle_startstop_min
= 0; /* how many minutes ago was the
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
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())) {
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
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
606 static int minutes_disk_activity
= 0; /* count minutes of hdd use during
608 static int last_disk_activity
= CHARGE_END_LONGD
+ 1; /* last hdd use x mins ago */
611 if (charger_input_state
== CHARGER_PLUGGED
) {
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
;
628 charge_state
= TOPOFF
;
629 target_voltage
= TOPOFF_VOLTAGE
;
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
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;
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;
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)) {
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)) {
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, "
724 *have charged too long and deltaV detection did not
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
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;
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]
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]
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
))
799 if((unsigned) battery_millivolts
< target_voltage
) {
801 pid_i
++; /* limit so it doesn't "wind up" */
805 pid_i
--; /* limit so it doesn't "wind up" */
809 trickle_sec
= pid_p
+ pid_i
;
811 if(trickle_sec
> 60) {
814 if(trickle_sec
< 0) {
818 } else if (charge_state
== DISCHARGING
) {
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.
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;
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
);
850 charger_enable(false);
851 power_thread_sleep(HZ
* (60 - trickle_sec
));
853 #if defined(DEBUG_FILE)
856 /* It is probably too late to close the file but we can try...*/
862 fd
= open(DEBUG_FILE_NAME
, O_WRONLY
| O_APPEND
| O_CREAT
);
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 */
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
));
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)
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
:
908 charge_state
= DISCHARGING
;
910 case CHARGER_PLUGGED
:
912 if (charging_state()) {
913 charge_state
= CHARGING
;
915 charge_state
= DISCHARGING
;
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)
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
946 static void power_thread_sleep(int ticks
)
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 */
962 || (usb_inserted() && usb_charging_enabled())
965 switch(charger_input_state
) {
967 case CHARGER_UNPLUGGED
:
968 charger_input_state
= CHARGER_PLUGGED
;
970 case CHARGER_PLUGGED
:
971 queue_broadcast(SYS_CHARGER_CONNECTED
, 0);
972 last_sent_battery_level
= 0;
973 charger_input_state
= CHARGER
;
978 } else { /* charger not inserted */
979 switch(charger_input_state
) {
982 case CHARGER_UNPLUGGED
:
983 queue_broadcast(SYS_CHARGER_DISCONNECTED
, 0);
984 last_sent_battery_level
= 100;
985 charger_input_state
= NO_CHARGER
;
987 case CHARGER_PLUGGED
:
989 charger_input_state
= CHARGER_UNPLUGGED
;
993 #endif /* CONFIG_CHARGING */
995 small_ticks
= MIN(HZ
/2, 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)
1007 #ifdef HAVE_RTC_ALARM
1008 power_thread_rtc_process();
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
]))
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 */
1054 while(battery_adc_voltage()>4200) /* gives false readings initially */
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 */
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
;
1075 if(charger_inserted()) {
1076 battery_percent
= voltage_to_percent(battery_millivolts
,
1077 percent_to_volt_charge
);
1080 { battery_percent
= voltage_to_percent(battery_millivolts
,
1081 percent_to_volt_discharge
[battery_type
]);
1082 battery_percent
+= (battery_percent
< 100);
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
)
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 */
1121 #ifdef HAVE_RECORDING
1122 if (audio_status() & AUDIO_STATUS_RECORD
)
1123 shutdown_timeout
+= HZ
*8;
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();
1141 shutdown_timeout
= 0;
1144 /* Various hardware housekeeping tasks relating to shutting down the jukebox */
1145 void shutdown_hw(void)
1148 charging_algorithm_close();
1150 if (battery_level_safe()) { /* do not save on critical battery */
1151 #ifdef HAVE_LCD_BITMAP
1154 if(ata_disk_is_active())
1157 while(ata_disk_is_active())
1160 #if CONFIG_CODEC != SWCODEC
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())
1171 lcd_set_contrast(0);
1172 #endif /* IAUDIO_X5 */
1173 #ifdef HAVE_REMOTE_LCD
1174 lcd_remote_set_contrast(0);
1177 #ifdef HAVE_LCD_SHUTDOWN
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
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
;
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
);