Add USB PID for Ipod Classic as incompatible variant of the Video. Remove PID for...
[Rockbox.git] / firmware / powermgmt.c
blob3d08c11ff5ebd27c883e46ef3c97a0b82567365b
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2002 by Heikki Hannikainen, Uwe Freese
11 * Revisions copyright (C) 2005 by Gerald Van Baren
13 * All files in this archive are subject to the GNU General Public License.
14 * See the file COPYING in the source tree root for full license agreement.
16 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
17 * KIND, either express or implied.
19 ****************************************************************************/
20 #include "config.h"
21 #include "cpu.h"
22 #include "kernel.h"
23 #include "thread.h"
24 #include "system.h"
25 #include "debug.h"
26 #include "panic.h"
27 #include "adc.h"
28 #include "string.h"
29 #include "sprintf.h"
30 #include "ata.h"
31 #include "power.h"
32 #include "button.h"
33 #include "audio.h"
34 #include "mp3_playback.h"
35 #include "usb.h"
36 #include "powermgmt.h"
37 #include "backlight.h"
38 #include "lcd.h"
39 #include "rtc.h"
40 #if CONFIG_TUNER
41 #include "fmradio.h"
42 #endif
43 #include "sound.h"
44 #ifdef HAVE_LCD_BITMAP
45 #include "font.h"
46 #endif
47 #if defined(HAVE_RECORDING) && (CONFIG_CODEC == SWCODEC)
48 #include "pcm_record.h"
49 #endif
50 #include "logf.h"
51 #include "lcd-remote.h"
52 #ifdef SIMULATOR
53 #include <time.h>
54 #endif
56 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
57 #include "pcf50606.h"
58 #include "lcd-remote-target.h"
59 #endif
62 * Define DEBUG_FILE to create a csv (spreadsheet) with battery information
63 * in it (one sample per minute). This is only for very low level debug.
65 #undef DEBUG_FILE
66 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
67 #include "file.h"
68 #define DEBUG_FILE_NAME "/powermgmt.csv"
69 #define DEBUG_MESSAGE_LEN 133
70 static char debug_message[DEBUG_MESSAGE_LEN];
71 #define DEBUG_STACK ((0x1000)/sizeof(long))
72 static int fd; /* write debug information to this file */
73 static int wrcount;
74 #else
75 #define DEBUG_STACK 0
76 #endif
78 static int shutdown_timeout = 0;
79 #if CONFIG_CHARGING >= CHARGING_MONITOR
80 charge_state_type charge_state; /* charging mode */
81 #endif
83 static void send_battery_level_event(void);
84 static int last_sent_battery_level = 100;
86 #if CONFIG_CHARGING
87 charger_input_state_type charger_input_state IDATA_ATTR;
88 #endif
90 #ifdef SIMULATOR /***********************************************************/
92 #define BATT_MINMVOLT 2500 /* minimum millivolts of battery */
93 #define BATT_MAXMVOLT 4500 /* maximum millivolts of battery */
94 #define BATT_MAXRUNTIME (10 * 60) /* maximum runtime with full battery in minutes */
96 static unsigned int battery_millivolts = (unsigned int)BATT_MAXMVOLT;
97 static int battery_percent = 100; /* battery capacity level in percent */
98 static int powermgmt_est_runningtime_min = BATT_MAXRUNTIME; /* estimated remaining time in minutes */
100 static void battery_status_update(void)
102 static time_t last_change = 0;
103 static bool charging = false;
104 time_t now;
106 time(&now);
107 if (last_change < now)
109 last_change = now;
111 /* change the values: */
112 if (charging)
114 if (battery_millivolts >= BATT_MAXMVOLT)
116 /* Pretend the charger was disconnected */
117 charging = false;
118 queue_broadcast(SYS_CHARGER_DISCONNECTED, 0);
119 last_sent_battery_level = 100;
122 else
124 if (battery_millivolts <= BATT_MINMVOLT)
126 /* Pretend the charger was connected */
127 charging = true;
128 queue_broadcast(SYS_CHARGER_CONNECTED, 0);
129 last_sent_battery_level = 0;
132 if (charging)
133 battery_millivolts += (BATT_MAXMVOLT - BATT_MINMVOLT) / 50;
134 else
135 battery_millivolts -= (BATT_MAXMVOLT - BATT_MINMVOLT) / 100;
137 battery_percent = 100 * (battery_millivolts - BATT_MINMVOLT) / (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 #if CONFIG_CHARGING == CHARGING_CONTROL
208 int long_delta; /* long term delta battery voltage */
209 int short_delta; /* short term delta battery voltage */
210 bool disk_activity_last_cycle = false; /* flag set to aid charger time
211 * calculation */
212 char power_message[POWER_MESSAGE_LEN] = ""; /* message that's shown in
213 debug menu */
214 /* percentage at which charging
215 starts */
216 int powermgmt_last_cycle_startstop_min = 0; /* how many minutes ago was the
217 charging started or
218 stopped? */
219 int powermgmt_last_cycle_level = 0; /* which level had the
220 batteries at this time? */
221 int trickle_sec = 0; /* how many seconds should the
222 charger be enabled per
223 minute for trickle
224 charging? */
225 int pid_p = 0; /* PID proportional term */
226 int pid_i = 0; /* PID integral term */
227 #endif /* CONFIG_CHARGING == CHARGING_CONTROL */
230 * Average battery voltage and charger voltage, filtered via a digital
231 * exponential filter.
233 static unsigned int avgbat; /* average battery voltage (filtering) */
234 static unsigned int battery_millivolts;/* filtered battery voltage, millivolts */
236 #ifdef HAVE_CHARGE_CTRL
237 #define BATT_AVE_SAMPLES 32 /* filter constant / @ 2Hz sample rate */
238 #else
239 #define BATT_AVE_SAMPLES 128 /* slw filter constant for all others */
240 #endif
242 /* battery level (0-100%) of this minute, updated once per minute */
243 static int battery_percent = -1;
244 static int battery_capacity = BATTERY_CAPACITY_DEFAULT; /* default value, mAh */
245 #if BATTERY_TYPES_COUNT > 1
246 static int battery_type = 0;
247 #else
248 #define battery_type 0
249 #endif
251 /* Power history: power_history[0] is the newest sample */
252 unsigned short power_history[POWER_HISTORY_LEN];
254 static char power_stack[DEFAULT_STACK_SIZE/2 + DEBUG_STACK];
255 static const char power_thread_name[] = "power";
257 static int poweroff_timeout = 0;
258 static int powermgmt_est_runningtime_min = -1;
260 static bool sleeptimer_active = false;
261 static long sleeptimer_endtick;
263 static long last_event_tick;
265 static int voltage_to_battery_level(int battery_millivolts);
266 static void battery_status_update(void);
267 static int runcurrent(void);
269 void battery_read_info(int *voltage, int *level)
271 int millivolts = battery_adc_voltage();
273 if (voltage)
274 *voltage = millivolts;
276 if (level)
277 *level = voltage_to_battery_level(millivolts);
280 void reset_poweroff_timer(void)
282 last_event_tick = current_tick;
285 #if BATTERY_TYPES_COUNT > 1
286 void set_battery_type(int type)
288 if (type != battery_type) {
289 battery_type = type;
290 battery_status_update(); /* recalculate the battery status */
293 #endif
295 void set_battery_capacity(int capacity)
297 battery_capacity = capacity;
298 if (battery_capacity > BATTERY_CAPACITY_MAX)
299 battery_capacity = BATTERY_CAPACITY_MAX;
300 if (battery_capacity < BATTERY_CAPACITY_MIN)
301 battery_capacity = BATTERY_CAPACITY_MIN;
302 battery_status_update(); /* recalculate the battery status */
305 int battery_time(void)
307 return powermgmt_est_runningtime_min;
310 /* Returns battery level in percent */
311 int battery_level(void)
313 return battery_percent;
316 /* Returns filtered battery voltage [millivolts] */
317 unsigned int battery_voltage(void)
319 return battery_millivolts;
322 /* Tells if the battery level is safe for disk writes */
323 bool battery_level_safe(void)
325 return battery_millivolts > battery_level_dangerous[battery_type];
328 void set_poweroff_timeout(int timeout)
330 poweroff_timeout = timeout;
333 void set_sleep_timer(int seconds)
335 if(seconds) {
336 sleeptimer_active = true;
337 sleeptimer_endtick = current_tick + seconds * HZ;
339 else {
340 sleeptimer_active = false;
341 sleeptimer_endtick = 0;
345 int get_sleep_timer(void)
347 if(sleeptimer_active)
348 return (sleeptimer_endtick - current_tick) / HZ;
349 else
350 return 0;
353 /* look into the percent_to_volt_* table and get a realistic battery level */
354 static int voltage_to_percent(int voltage, const short* table)
356 if (voltage <= table[0])
357 return 0;
358 else
359 if (voltage >= table[10])
360 return 100;
361 else {
362 /* search nearest value */
363 int i = 0;
364 while ((i < 10) && (table[i+1] < voltage))
365 i++;
366 /* interpolate linear between the smaller and greater value */
367 return (i * 10) /* Tens digit, 10% per entry */
368 + (((voltage - table[i]) * 10)
369 / (table[i+1] - table[i])); /* Ones digit: interpolated */
373 /* update battery level and estimated runtime, called once per minute or
374 * when battery capacity / type settings are changed */
375 static int voltage_to_battery_level(int battery_millivolts)
377 int level;
379 #if defined(CONFIG_CHARGER) \
380 && (defined(IRIVER_H100_SERIES) || defined(IRIVER_H300_SERIES))
381 /* Checking for iriver is a temporary kludge.
382 * This code needs rework/unification */
383 if (charger_input_state == NO_CHARGER) {
384 /* discharging. calculate new battery level and average with last */
385 level = voltage_to_percent(battery_millivolts,
386 percent_to_volt_discharge[battery_type]);
387 if (level != (battery_percent - 1))
388 level = (level + battery_percent + 1) / 2;
390 else if (charger_input_state == CHARGER_UNPLUGGED) {
391 /* just unplugged. adjust filtered values */
392 battery_millivolts -= percent_to_volt_charge[battery_percent/10] -
393 percent_to_volt_discharge[0][battery_percent/10];
394 avgbat = battery_millivolts * 1000 * BATT_AVE_SAMPLES;
395 level = battery_percent;
397 else if (charger_input_state == CHARGER_PLUGGED) {
398 /* just plugged in. adjust battery values */
399 battery_millivolts += percent_to_volt_charge[battery_percent/10] -
400 percent_to_volt_discharge[0][battery_percent/10];
401 avgbat = battery_millivolts * 1000 * BATT_AVE_SAMPLES;
402 level = MIN(12 * battery_percent / 10, 99);
404 else { /* charging. calculate new battery level */
405 level = voltage_to_percent(battery_millivolts,
406 percent_to_volt_charge);
408 #elif CONFIG_CHARGING >= CHARGING_MONITOR
409 if (charge_state == DISCHARGING) {
410 level = voltage_to_percent(battery_millivolts,
411 percent_to_volt_discharge[battery_type]);
413 else if (charge_state == CHARGING) {
414 /* battery level is defined to be < 100% until charging is finished */
415 level = MIN(voltage_to_percent(battery_millivolts,
416 percent_to_volt_charge), 99);
418 else { /* in topoff/trickle charge, battery is by definition 100% full */
419 level = 100;
421 #else
422 /* always use the discharge table */
423 level = voltage_to_percent(battery_millivolts,
424 percent_to_volt_discharge[battery_type]);
425 #endif
427 return level;
430 static void battery_status_update(void)
432 int level = voltage_to_battery_level(battery_millivolts);
434 /* calculate estimated remaining running time */
435 /* discharging: remaining running time */
436 /* charging: remaining charging time */
437 #if CONFIG_CHARGING >= CHARGING_MONITOR
438 if (charge_state == CHARGING) {
439 powermgmt_est_runningtime_min = (100 - level) * battery_capacity * 60
440 / 100 / (CURRENT_MAX_CHG - runcurrent());
442 else
443 #elif CONFIG_CHARGING \
444 && (defined(IRIVER_H100_SERIES) || defined(IRIVER_H300_SERIES))
445 /* Checking for iriver is a temporary kludge.
446 * This code needs rework/unification */
447 if (charger_inserted()) {
448 #ifdef IRIVER_H300_SERIES
449 /* H300_SERIES use CURRENT_MAX_CHG for basic charge time (80%)
450 * plus 110 min top off charge time */
451 powermgmt_est_runningtime_min = ((100-level) * battery_capacity * 80
452 /100 / CURRENT_MAX_CHG) + 110;
453 #else
454 /* H100_SERIES scaled for 160 min basic charge time (80%) on
455 * 1600 mAh battery plus 110 min top off charge time */
456 powermgmt_est_runningtime_min = ((100 - level) * battery_capacity
457 / 993) + 110;
458 #endif
459 level = (level * 80) / 100;
460 if (level > 72) { /* > 91% */
461 int i = POWER_HISTORY_LEN;
462 int d = 1;
463 #ifdef HAVE_CHARGE_STATE
464 if (charge_state == DISCHARGING)
465 d = -2;
466 #endif
467 while ((i > 2) && (d > 0)) /* search zero or neg. delta */
468 d = power_history[0] - power_history[--i];
469 if ((((d == 0) && (i > 6)) || (d == -1)) && (i < 118)) {
470 /* top off charging */
471 level = MIN(80 + (i*19 / 113), 99); /* show 81% .. 99% */
472 powermgmt_est_runningtime_min = MAX(116 - i, 0);
474 else if ((d < 0) || (i > 117)) {
475 /* charging finished */
476 level = 100;
477 powermgmt_est_runningtime_min = battery_capacity * 60
478 / runcurrent();
482 else
483 #endif /* BATT_LIPOL1300 */
485 if ((battery_millivolts + 20) > percent_to_volt_discharge[0][0])
486 powermgmt_est_runningtime_min = (level + battery_percent) * 60 *
487 battery_capacity / 200 / runcurrent();
489 else if (battery_millivolts <= battery_level_shutoff[0])
490 powermgmt_est_runningtime_min = 0;
492 else
493 powermgmt_est_runningtime_min = (battery_millivolts -
494 battery_level_shutoff[0]) / 2;
497 battery_percent = level;
498 send_battery_level_event();
502 * We shut off in the following cases:
503 * 1) The unit is idle, not playing music
504 * 2) The unit is playing music, but is paused
505 * 3) The battery level has reached shutdown limit
507 * We do not shut off in the following cases:
508 * 1) The USB is connected
509 * 2) The charger is connected
510 * 3) We are recording, or recording with pause
511 * 4) The radio is playing
513 static void handle_auto_poweroff(void)
515 long timeout = poweroff_timeout*60*HZ;
516 int audio_stat = audio_status();
518 #if CONFIG_CHARGING
520 * Inhibit shutdown as long as the charger is plugged in. If it is
521 * unplugged, wait for a timeout period and then shut down.
523 if(charger_input_state == CHARGER || audio_stat == AUDIO_STATUS_PLAY) {
524 last_event_tick = current_tick;
526 #endif
528 #ifndef NO_LOW_BATTERY_SHUTDOWN
529 /* switch off unit if battery level is too low for reliable operation */
530 if(battery_millivolts < battery_level_shutoff[battery_type]) {
531 if(!shutdown_timeout) {
532 backlight_on();
533 sys_poweroff();
536 #endif
538 if(timeout &&
539 #if CONFIG_TUNER && !defined(BOOTLOADER)
540 (!(get_radio_status() & FMRADIO_PLAYING)) &&
541 #endif
542 !usb_inserted() &&
543 ((audio_stat == 0) ||
544 ((audio_stat == (AUDIO_STATUS_PLAY | AUDIO_STATUS_PAUSE)) &&
545 !sleeptimer_active)))
547 if(TIME_AFTER(current_tick, last_event_tick + timeout) &&
548 TIME_AFTER(current_tick, last_disk_activity + timeout))
550 sys_poweroff();
553 else
555 /* Handle sleeptimer */
556 if(sleeptimer_active && !usb_inserted())
558 if(TIME_AFTER(current_tick, sleeptimer_endtick))
560 audio_stop();
561 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
562 if((charger_input_state == CHARGER) ||
563 (charger_input_state == CHARGER_PLUGGED))
565 DEBUGF("Sleep timer timeout. Stopping...\n");
566 set_sleep_timer(0);
567 backlight_off(); /* Nighty, nighty... */
569 else
570 #endif
572 DEBUGF("Sleep timer timeout. Shutting off...\n");
573 sys_poweroff();
581 * Estimate how much current we are drawing just to run.
583 static int runcurrent(void)
585 int current;
587 #if MEM == 8 && !defined(HAVE_MMC)
588 /* assuming 192 kbps, the running time is 22% longer with 8MB */
589 current = (CURRENT_NORMAL*100/122);
590 #else
591 current = CURRENT_NORMAL;
592 #endif /* MEM == 8 */
594 if(usb_inserted()
595 #if defined(HAVE_USB_POWER)
596 #if (CURRENT_USB < CURRENT_NORMAL)
597 || usb_powered()
598 #else
599 && !usb_powered()
600 #endif
601 #endif
604 current = CURRENT_USB;
607 #if defined(HAVE_BACKLIGHT) && !defined(BOOTLOADER)
608 if (backlight_get_current_timeout() == 0) /* LED always on */
609 current += CURRENT_BACKLIGHT;
610 #endif
612 #if defined(HAVE_RECORDING) && defined(CURRENT_RECORD)
613 if (audio_status() & AUDIO_STATUS_RECORD)
614 current += CURRENT_RECORD;
615 #endif
617 #ifdef HAVE_SPDIF_POWER
618 if (spdif_powered())
619 current += CURRENT_SPDIF_OUT;
620 #endif
622 #ifdef HAVE_REMOTE_LCD
623 if (remote_detect())
624 current += CURRENT_REMOTE;
625 #endif
627 return(current);
631 /* Check to see whether or not we've received an alarm in the last second */
632 #ifdef HAVE_RTC_ALARM
633 static void power_thread_rtc_process(void)
635 if (rtc_check_alarm_flag()) {
636 rtc_enable_alarm(false);
639 #endif
642 * This function is called to do the relativly long sleep waits from within the
643 * main power_thread loop while at the same time servicing any other periodic
644 * functions in the power thread which need to be called at a faster periodic
645 * rate than the slow periodic rate of the main power_thread loop.
647 * While we are waiting for the time to expire, we average the battery
648 * voltages.
650 static void power_thread_sleep(int ticks)
652 int small_ticks;
654 while (ticks > 0) {
656 #if CONFIG_CHARGING
658 * Detect charger plugged/unplugged transitions. On a plugged or
659 * unplugged event, we return immediately, run once through the main
660 * loop (including the subroutines), and end up back here where we
661 * transition to the appropriate steady state charger on/off state.
663 if(charger_inserted()
664 #ifdef HAVE_USB_POWER /* USB powered or USB inserted both provide power */
665 || usb_powered()
666 #if CONFIG_CHARGING
667 || (usb_inserted() && usb_charging_enabled())
668 #endif
669 #endif
671 switch(charger_input_state) {
672 case NO_CHARGER:
673 case CHARGER_UNPLUGGED:
674 charger_input_state = CHARGER_PLUGGED;
675 return;
676 case CHARGER_PLUGGED:
677 queue_broadcast(SYS_CHARGER_CONNECTED, 0);
678 last_sent_battery_level = 0;
679 charger_input_state = CHARGER;
680 break;
681 case CHARGER:
682 break;
684 } else { /* charger not inserted */
685 switch(charger_input_state) {
686 case NO_CHARGER:
687 break;
688 case CHARGER_UNPLUGGED:
689 queue_broadcast(SYS_CHARGER_DISCONNECTED, 0);
690 last_sent_battery_level = 100;
691 charger_input_state = NO_CHARGER;
692 break;
693 case CHARGER_PLUGGED:
694 case CHARGER:
695 charger_input_state = CHARGER_UNPLUGGED;
696 return;
699 #endif
700 #if CONFIG_CHARGING == CHARGING_MONITOR
701 switch (charger_input_state) {
702 case CHARGER_UNPLUGGED:
703 case NO_CHARGER:
704 charge_state = DISCHARGING;
705 break;
706 case CHARGER_PLUGGED:
707 case CHARGER:
708 if (charging_state()) {
709 charge_state = CHARGING;
710 } else {
711 charge_state = DISCHARGING;
713 break;
716 #endif /* CONFIG_CHARGING == CHARGING_MONITOR */
718 small_ticks = MIN(HZ/2, ticks);
719 sleep(small_ticks);
720 ticks -= small_ticks;
722 /* If the power off timeout expires, the main thread has failed
723 to shut down the system, and we need to force a power off */
724 if(shutdown_timeout) {
725 shutdown_timeout -= small_ticks;
726 if(shutdown_timeout <= 0)
727 power_off();
730 #ifdef HAVE_RTC_ALARM
731 power_thread_rtc_process();
732 #endif
735 * Do a digital exponential filter. We don't sample the battery if
736 * the disk is spinning unless we are in USB mode (the disk will most
737 * likely always be spinning in USB mode).
739 if (!ata_disk_is_active() || usb_inserted()) {
740 avgbat += battery_adc_voltage() - (avgbat / BATT_AVE_SAMPLES);
742 * battery_millivolts is the millivolt-scaled filtered battery value.
744 battery_millivolts = avgbat / BATT_AVE_SAMPLES;
746 /* update battery status every time an update is available */
747 battery_status_update();
749 else if (battery_percent < 8) {
750 /* If battery is low, observe voltage during disk activity.
751 * Shut down if voltage drops below shutoff level and we are not
752 * using NiMH or Alkaline batteries.
754 battery_millivolts = (battery_adc_voltage() +
755 battery_millivolts + 1) / 2;
757 /* update battery status every time an update is available */
758 battery_status_update();
760 #ifndef NO_LOW_BATTERY_SHUTDOWN
761 if (!shutdown_timeout &&
762 (battery_millivolts < battery_level_shutoff[battery_type]))
763 sys_poweroff();
764 else
765 #endif
766 avgbat += battery_millivolts - (avgbat / BATT_AVE_SAMPLES);
769 #if CONFIG_CHARGING == CHARGING_CONTROL
770 if (ata_disk_is_active()) {
771 /* flag hdd use for charging calculation */
772 disk_activity_last_cycle = true;
774 #endif
775 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
777 * If we have a lot of pending writes or if the disk is spining,
778 * fsync the debug log file.
780 if((wrcount > 10) || ((wrcount > 0) && ata_disk_is_active())) {
781 fsync(fd);
782 wrcount = 0;
784 #endif
790 * This power thread maintains a history of battery voltage
791 * and implements a charging algorithm.
792 * For a complete description of the charging algorithm read
793 * docs/CHARGING_ALGORITHM.
796 static void power_thread(void)
798 #if CONFIG_CHARGING == CHARGING_CONTROL
799 int i;
800 unsigned int target_voltage = TRICKLE_VOLTAGE; /* desired topoff/trickle
801 * voltage level */
802 int charge_max_time_idle = 0; /* max. charging duration, calculated at
803 * beginning of charging */
804 int charge_max_time_now = 0; /* max. charging duration including
805 * hdd activity */
806 int minutes_disk_activity = 0; /* count minutes of hdd use during
807 * charging */
808 int last_disk_activity = CHARGE_END_LONGD + 1; /* last hdd use x mins ago */
809 #endif
811 /* Delay reading the first battery level */
812 #ifdef MROBE_100
813 while(battery_adc_voltage()>4200) /* gives false readings initially */
814 #endif
815 sleep(HZ/100);
817 /* initialize the voltages for the exponential filter */
818 avgbat = battery_adc_voltage() + 15;
820 #ifndef HAVE_MMC /* this adjustment is only needed for HD based */
821 /* The battery voltage is usually a little lower directly after
822 turning on, because the disk was used heavily. Raise it by 5% */
823 #ifdef HAVE_CHARGING
824 if(!charger_inserted()) /* only if charger not connected */
825 #endif
826 avgbat += (percent_to_volt_discharge[battery_type][6] -
827 percent_to_volt_discharge[battery_type][5]) / 2;
828 #endif /* not HAVE_MMC */
830 avgbat = avgbat * BATT_AVE_SAMPLES;
831 battery_millivolts = avgbat / BATT_AVE_SAMPLES;
833 #if CONFIG_CHARGING
834 if(charger_inserted()) {
835 battery_percent = voltage_to_percent(battery_millivolts,
836 percent_to_volt_charge);
837 #if defined(IRIVER_H100_SERIES) || defined(IRIVER_H300_SERIES)
838 /* Checking for iriver is a temporary kludge. */
839 charger_input_state = CHARGER;
840 #endif
841 } else
842 #endif
843 { battery_percent = voltage_to_percent(battery_millivolts,
844 percent_to_volt_discharge[battery_type]);
845 battery_percent += (battery_percent < 100);
848 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
849 fd = -1;
850 wrcount = 0;
851 #endif
853 while (1)
855 /* rotate the power history */
856 memmove(power_history + 1, power_history,
857 sizeof(power_history) - sizeof(power_history[0]));
859 /* insert new value at the start, in millivolts 8-) */
860 power_history[0] = battery_millivolts;
862 #if CONFIG_CHARGING == CHARGING_CONTROL
863 if (charger_input_state == CHARGER_PLUGGED) {
864 pid_p = 0;
865 pid_i = 0;
866 snprintf(power_message, POWER_MESSAGE_LEN, "Charger plugged in");
868 * The charger was just plugged in. If the battery level is
869 * nearly charged, just trickle. If the battery is low, start
870 * a full charge cycle. If the battery level is in between,
871 * top-off and then trickle.
873 if(battery_percent > START_TOPOFF_CHG) {
874 powermgmt_last_cycle_level = battery_percent;
875 powermgmt_last_cycle_startstop_min = 0;
876 if(battery_percent >= START_TRICKLE_CHG) {
877 charge_state = TRICKLE;
878 target_voltage = TRICKLE_VOLTAGE;
879 } else {
880 charge_state = TOPOFF;
881 target_voltage = TOPOFF_VOLTAGE;
883 } else {
885 * Start the charger full strength
887 i = CHARGE_MAX_TIME_1500 * battery_capacity / 1500;
888 charge_max_time_idle =
889 i * (100 + 35 - battery_percent) / 100;
890 if (charge_max_time_idle > i) {
891 charge_max_time_idle = i;
893 charge_max_time_now = charge_max_time_idle;
895 snprintf(power_message, POWER_MESSAGE_LEN,
896 "ChgAt %d%% max %dm", battery_level(),
897 charge_max_time_now);
899 /* enable the charger after the max time calc is done,
900 because battery_level depends on if the charger is
901 on */
902 DEBUGF("power: charger inserted and battery"
903 " not full, charging\n");
904 powermgmt_last_cycle_level = battery_percent;
905 powermgmt_last_cycle_startstop_min = 0;
906 trickle_sec = 60;
907 long_delta = short_delta = 999999;
908 charge_state = CHARGING;
911 if (charge_state == CHARGING) {
912 /* alter charge time max length with extra disk use */
913 if (disk_activity_last_cycle) {
914 minutes_disk_activity++;
915 charge_max_time_now = charge_max_time_idle +
916 (minutes_disk_activity * 2 / 5);
917 disk_activity_last_cycle = false;
918 last_disk_activity = 0;
919 } else {
920 last_disk_activity++;
923 * Check the delta voltage over the last X minutes so we can do
924 * our end-of-charge logic based on the battery level change.
925 *(no longer use minimum time as logic for charge end has 50
926 * minutes minimum charge built in)
928 if (powermgmt_last_cycle_startstop_min > CHARGE_END_SHORTD) {
929 short_delta = power_history[0] -
930 power_history[CHARGE_END_SHORTD - 1];
933 if (powermgmt_last_cycle_startstop_min > CHARGE_END_LONGD) {
935 * Scan the history: the points where measurement is taken need to
936 * be fairly static. (check prior to short delta 'area')
937 * (also only check first and last 10 cycles - delta in middle OK)
939 long_delta = power_history[0] -
940 power_history[CHARGE_END_LONGD - 1];
942 for(i = CHARGE_END_SHORTD; i < CHARGE_END_SHORTD + 10; i++) {
943 if(((power_history[i] - power_history[i+1]) > 50) ||
944 ((power_history[i] - power_history[i+1]) < -50)) {
945 long_delta = 777777;
946 break;
949 for(i = CHARGE_END_LONGD - 11; i < CHARGE_END_LONGD - 1 ; i++) {
950 if(((power_history[i] - power_history[i+1]) > 50) ||
951 ((power_history[i] - power_history[i+1]) < -50)) {
952 long_delta = 888888;
953 break;
958 snprintf(power_message, POWER_MESSAGE_LEN,
959 "Chg %dm, max %dm", powermgmt_last_cycle_startstop_min,
960 charge_max_time_now);
962 * End of charge criteria (any qualify):
963 * 1) Charged a long time
964 * 2) DeltaV went negative for a short time ( & long delta static)
965 * 3) DeltaV was negative over a longer period (no disk use only)
966 * Note: short_delta and long_delta are millivolts
968 if ((powermgmt_last_cycle_startstop_min >= charge_max_time_now) ||
969 (short_delta <= -50 && long_delta < 50 ) || (long_delta < -20 &&
970 last_disk_activity > CHARGE_END_LONGD)) {
971 if (powermgmt_last_cycle_startstop_min > charge_max_time_now) {
972 DEBUGF("power: powermgmt_last_cycle_startstop_min > charge_max_time_now, "
973 "enough!\n");
975 *have charged too long and deltaV detection did not
976 *work!
978 snprintf(power_message, POWER_MESSAGE_LEN,
979 "Chg tmout %d min", charge_max_time_now);
981 * Switch to trickle charging. We skip the top-off
982 * since we've effectively done the top-off operation
983 * already since we charged for the maximum full
984 * charge time.
986 powermgmt_last_cycle_level = battery_percent;
987 powermgmt_last_cycle_startstop_min = 0;
988 charge_state = TRICKLE;
991 * set trickle charge target to a relative voltage instead
992 * of an arbitrary value - the fully charged voltage may
993 * vary according to ambient temp, battery condition etc
994 * trickle target is -0.15v from full voltage acheived
995 * topup target is -0.05v from full voltage
997 target_voltage = power_history[0] - 150;
999 } else {
1000 if(short_delta <= -5) {
1001 DEBUGF("power: short-term negative"
1002 " delta, enough!\n");
1003 snprintf(power_message, POWER_MESSAGE_LEN,
1004 "end negd %d %dmin", short_delta,
1005 powermgmt_last_cycle_startstop_min);
1006 target_voltage = power_history[CHARGE_END_SHORTD - 1]
1007 - 50;
1008 } else {
1009 DEBUGF("power: long-term small "
1010 "positive delta, enough!\n");
1011 snprintf(power_message, POWER_MESSAGE_LEN,
1012 "end lowd %d %dmin", long_delta,
1013 powermgmt_last_cycle_startstop_min);
1014 target_voltage = power_history[CHARGE_END_LONGD - 1]
1015 - 50;
1018 * Switch to top-off charging.
1020 powermgmt_last_cycle_level = battery_percent;
1021 powermgmt_last_cycle_startstop_min = 0;
1022 charge_state = TOPOFF;
1026 else if (charge_state != DISCHARGING) /* top off or trickle */
1029 *Time to switch from topoff to trickle?
1031 if ((charge_state == TOPOFF) &&
1032 (powermgmt_last_cycle_startstop_min > TOPOFF_MAX_TIME))
1034 powermgmt_last_cycle_level = battery_percent;
1035 powermgmt_last_cycle_startstop_min = 0;
1036 charge_state = TRICKLE;
1037 target_voltage = target_voltage - 100;
1040 * Adjust trickle charge time (proportional and integral terms).
1041 * Note: I considered setting the level higher if the USB is
1042 * plugged in, but it doesn't appear to be necessary and will
1043 * generate more heat [gvb].
1046 pid_p = ((signed)target_voltage - (signed)battery_millivolts) / 5;
1047 if((pid_p <= PID_DEADZONE) && (pid_p >= -PID_DEADZONE))
1048 pid_p = 0;
1050 if((unsigned) battery_millivolts < target_voltage) {
1051 if(pid_i < 60) {
1052 pid_i++; /* limit so it doesn't "wind up" */
1054 } else {
1055 if(pid_i > 0) {
1056 pid_i--; /* limit so it doesn't "wind up" */
1060 trickle_sec = pid_p + pid_i;
1062 if(trickle_sec > 60) {
1063 trickle_sec = 60;
1065 if(trickle_sec < 0) {
1066 trickle_sec = 0;
1069 } else if (charge_state == DISCHARGING) {
1070 trickle_sec = 0;
1072 * The charger is enabled here only in one case: if it was
1073 * turned on at boot time (power_init). Turn it off now.
1075 if (charger_enabled)
1076 charger_enable(false);
1079 if (charger_input_state == CHARGER_UNPLUGGED) {
1081 * The charger was just unplugged.
1083 DEBUGF("power: charger disconnected, disabling\n");
1085 charger_enable(false);
1086 powermgmt_last_cycle_level = battery_percent;
1087 powermgmt_last_cycle_startstop_min = 0;
1088 trickle_sec = 0;
1089 pid_p = 0;
1090 pid_i = 0;
1091 charge_state = DISCHARGING;
1092 snprintf(power_message, POWER_MESSAGE_LEN, "Charger: discharge");
1095 #endif /* CONFIG_CHARGING == CHARGING_CONTROL */
1097 /* sleep for a minute */
1099 #if CONFIG_CHARGING == CHARGING_CONTROL
1100 if(trickle_sec > 0) {
1101 charger_enable(true);
1102 power_thread_sleep(HZ * trickle_sec);
1104 if(trickle_sec < 60)
1105 charger_enable(false);
1106 power_thread_sleep(HZ * (60 - trickle_sec));
1107 #else
1108 power_thread_sleep(HZ * 60);
1109 #endif
1111 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1112 if(usb_inserted()) {
1113 if(fd >= 0) {
1114 /* It is probably too late to close the file but we can try...*/
1115 close(fd);
1116 fd = -1;
1118 } else {
1119 if(fd < 0) {
1120 fd = open(DEBUG_FILE_NAME, O_WRONLY | O_APPEND | O_CREAT);
1121 if(fd >= 0) {
1122 snprintf(debug_message, DEBUG_MESSAGE_LEN,
1123 "cycle_min, bat_millivolts, bat_percent, chgr_state, charge_state, pid_p, pid_i, trickle_sec\n");
1124 write(fd, debug_message, strlen(debug_message));
1125 wrcount = 99; /* force a flush */
1128 if(fd >= 0) {
1129 snprintf(debug_message, DEBUG_MESSAGE_LEN,
1130 "%d, %d, %d, %d, %d, %d, %d, %d\n",
1131 powermgmt_last_cycle_startstop_min, battery_millivolts,
1132 battery_percent, charger_input_state, charge_state,
1133 pid_p, pid_i, trickle_sec);
1134 write(fd, debug_message, strlen(debug_message));
1135 wrcount++;
1138 #endif
1139 handle_auto_poweroff();
1141 #if CONFIG_CHARGING == CHARGING_CONTROL
1142 powermgmt_last_cycle_startstop_min++;
1143 #endif
1147 void powermgmt_init(void)
1149 /* init history to 0 */
1150 memset(power_history, 0x00, sizeof(power_history));
1151 create_thread(power_thread, power_stack, sizeof(power_stack), 0,
1152 power_thread_name IF_PRIO(, PRIORITY_SYSTEM)
1153 IF_COP(, CPU));
1156 #endif /* SIMULATOR */
1158 void sys_poweroff(void)
1160 logf("sys_poweroff()");
1161 /* If the main thread fails to shut down the system, we will force a
1162 power off after an 20 second timeout - 28 seconds if recording */
1163 if (shutdown_timeout == 0)
1165 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1166 pcf50606_reset_timeout(); /* Reset timer on first attempt only */
1167 #endif
1168 #ifdef HAVE_RECORDING
1169 if (audio_status() & AUDIO_STATUS_RECORD)
1170 shutdown_timeout += HZ*8;
1171 #endif
1172 shutdown_timeout += HZ*20;
1175 queue_broadcast(SYS_POWEROFF, 0);
1178 void cancel_shutdown(void)
1180 logf("sys_cancel_shutdown()");
1182 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1183 /* TODO: Move some things to target/ tree */
1184 if (shutdown_timeout)
1185 pcf50606_reset_timeout();
1186 #endif
1188 shutdown_timeout = 0;
1191 /* Various hardware housekeeping tasks relating to shutting down the jukebox */
1192 void shutdown_hw(void)
1194 #ifndef SIMULATOR
1195 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1196 if(fd >= 0) {
1197 close(fd);
1198 fd = -1;
1200 #endif
1201 audio_stop();
1202 if (battery_level_safe()) { /* do not save on critical battery */
1203 #ifdef HAVE_LCD_BITMAP
1204 glyph_cache_save();
1205 #endif
1206 if(ata_disk_is_active())
1207 ata_spindown(1);
1209 while(ata_disk_is_active())
1210 sleep(HZ/10);
1212 #if CONFIG_CODEC != SWCODEC
1213 mp3_shutdown();
1214 #else
1215 audiohw_close();
1216 #endif
1218 /* If HD is still active we try to wait for spindown, otherwise the
1219 shutdown_timeout in power_thread_sleep will force a power off */
1220 while(ata_disk_is_active())
1221 sleep(HZ/10);
1222 #ifndef IAUDIO_X5
1223 lcd_set_contrast(0);
1224 #endif /* IAUDIO_X5 */
1225 #ifdef HAVE_REMOTE_LCD
1226 lcd_remote_set_contrast(0);
1227 #endif
1229 #ifdef HAVE_LCD_SHUTDOWN
1230 lcd_shutdown();
1231 #endif
1233 /* Small delay to make sure all HW gets time to flush. Especially
1234 eeprom chips are quite slow and might be still writing the last
1235 byte. */
1236 sleep(HZ/4);
1237 power_off();
1238 #endif /* #ifndef SIMULATOR */
1241 /* Send system battery level update events on reaching certain significant
1242 levels. This must be called after battery_percent has been updated. */
1243 static void send_battery_level_event(void)
1245 static const int levels[] = { 5, 15, 30, 50, 0 };
1246 const int *level = levels;
1247 while (*level)
1249 if (battery_percent <= *level && last_sent_battery_level > *level)
1251 last_sent_battery_level = *level;
1252 queue_broadcast(SYS_BATTERY_UPDATE, last_sent_battery_level);
1253 break;
1255 level++;