Ignore HAVE_BACKLIGHT for plugins, as they build without the check and makes life...
[maemo-rb.git] / firmware / powermgmt.c
bloba202c71bbfd918f48b5bd2d6cf056baba22d632e
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 #if CONFIG_CHARGING
84 charger_input_state_type charger_input_state IDATA_ATTR;
85 #endif
87 #ifdef SIMULATOR /***********************************************************/
89 #define BATT_MINCVOLT 250 /* minimum centivolts of battery */
90 #define BATT_MAXCVOLT 450 /* maximum centivolts of battery */
91 #define BATT_MAXRUNTIME (10 * 60) /* maximum runtime with full battery in minutes */
93 static unsigned int batt_centivolts = (unsigned int)BATT_MAXCVOLT;
94 static int batt_level = 100; /* battery capacity level in percent */
95 static int batt_time = BATT_MAXRUNTIME; /* estimated remaining time in minutes */
96 static time_t last_change = 0;
98 static void battery_status_update(void)
100 time_t now;
102 time(&now);
103 if (last_change < now) {
104 last_change = now;
106 /* change the values: */
107 batt_centivolts -= (unsigned int)(BATT_MAXCVOLT - BATT_MINCVOLT) / 101;
108 if (batt_centivolts < (unsigned int)BATT_MINCVOLT)
109 batt_centivolts = (unsigned int)BATT_MAXCVOLT;
111 batt_level = 100 * (batt_centivolts - BATT_MINCVOLT) / (BATT_MAXCVOLT - BATT_MINCVOLT);
112 batt_time = batt_level * BATT_MAXRUNTIME / 100;
116 void battery_read_info(int *adc, int *voltage, int *level)
118 battery_status_update();
120 if (adc)
121 *adc = batt_centivolts; /* just return something */
123 if (voltage)
124 *voltage = batt_centivolts;
126 if (level)
127 *level = batt_level;
130 unsigned int battery_voltage(void)
132 battery_status_update();
133 return batt_centivolts;
136 int battery_level(void)
138 battery_status_update();
139 return batt_level;
142 int battery_time(void)
144 battery_status_update();
145 return batt_time;
148 bool battery_level_safe(void)
150 return battery_level() >= 10;
153 void set_poweroff_timeout(int timeout)
155 (void)timeout;
158 void set_battery_capacity(int capacity)
160 (void)capacity;
163 #if BATTERY_TYPES_COUNT > 1
164 void set_battery_type(int type)
166 (void)type;
168 #endif
170 void reset_poweroff_timer(void)
174 #else /* not SIMULATOR ******************************************************/
176 static const unsigned char poweroff_idle_timeout_value[15] =
178 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 30, 45, 60
181 static const unsigned short battery_level_dangerous[BATTERY_TYPES_COUNT] =
183 #if CONFIG_BATTERY == BATT_LIION2200 /* FM Recorder, LiIon */
185 #elif CONFIG_BATTERY == BATT_3AAA /* Ondio: Alkaline, NiHM */
186 310, 345
187 #elif CONFIG_BATTERY == BATT_1AA /* iRiver iFP: Alkaline, NiHM */
188 105, 115
189 #elif CONFIG_BATTERY == BATT_LIPOL1300 /* iRiver H1x0: LiPolymer */
191 #elif CONFIG_BATTERY == BATT_LIION300 /* ipod nano */
193 #elif CONFIG_BATTERY == BATT_LIION400 /* iPOD Video 30GB */
195 #elif CONFIG_BATTERY == BATT_LIION750 /* Sansa e200 */
197 #elif CONFIG_BATTERY == BATT_LIION830 /* Gigabeat F */
199 #elif CONFIG_BATTERY == BATT_IAUDIO_X5M5 /* iAudio X5 */
201 #elif CONFIG_BATTERY == BATT_LPCS355385 /* iriver H10 20GB: LiPolymer*/
203 #elif CONFIG_BATTERY == BATT_BP009 /* iriver H10 5/6GB: LiPolymer */
205 #else /* Player/recorder: NiMH */
207 #endif
210 static const unsigned short battery_level_shutoff[BATTERY_TYPES_COUNT] =
212 #if CONFIG_BATTERY == BATT_LIION2200 /* FM Recorder */
214 #elif CONFIG_BATTERY == BATT_3AAA /* Ondio */
215 270, 280
216 #elif CONFIG_BATTERY == BATT_LIPOL1300 /* iRiver Hxxx */
218 #elif CONFIG_BATTERY == BATT_LIION300 /* ipod nano */
220 #elif CONFIG_BATTERY == BATT_LIION400 /* iPOD Video 30GB */
222 #elif CONFIG_BATTERY == BATT_LIION750 /* Sansa e200 */
224 #elif CONFIG_BATTERY == BATT_LIION830 /* Gigabeat F */
226 #elif CONFIG_BATTERY == BATT_IAUDIO_X5M5 /* iAudio X5 */
228 #elif CONFIG_BATTERY == BATT_LPCS355385 /* iriver H10 20GB */
230 #elif CONFIG_BATTERY == BATT_BP009 /* iriver H10 5/6GB */
232 #else /* Player/recorder: NiMH */
234 #endif
237 /* voltages (centivolt) of 0%, 10%, ... 100% when charging disabled */
238 static const unsigned short percent_to_volt_discharge[BATTERY_TYPES_COUNT][11] =
240 #if CONFIG_BATTERY == BATT_LIION2200
241 /* measured values */
242 { 260, 285, 295, 303, 311, 320, 330, 345, 360, 380, 400 }
243 #elif CONFIG_BATTERY == BATT_3AAA
244 /* measured values */
245 { 280, 325, 341, 353, 364, 374, 385, 395, 409, 427, 475 }, /* Alkaline */
246 { 310, 355, 363, 369, 372, 374, 376, 378, 380, 386, 405 } /* NiMH */
247 #elif CONFIG_BATTERY == BATT_LIPOL1300
248 /* Below 337 the backlight starts flickering during HD access */
249 { 337, 365, 370, 374, 378, 382, 387, 393, 400, 408, 416 }
250 #elif CONFIG_BATTERY == BATT_IAUDIO_X5M5
251 /* average measured values from X5 and M5L */
252 { 350, 365, 372, 374, 376, 379, 384, 390, 395, 404, 412 }
253 #elif CONFIG_BATTERY == BATT_LPCS355385
254 /* iriver H10 20GB */
255 { 376, 380, 385, 387, 390, 395, 402, 407, 411, 418, 424 }
256 #elif CONFIG_BATTERY == BATT_BP009
257 /* iriver H10 5/6GB */
258 { 372, 374, 380, 382, 384, 388, 394, 402, 406, 415, 424 }
259 #elif CONFIG_BATTERY == BATT_1AA
260 /* These values are the same as for 3AAA divided by 3. */
261 /* May need recalibration. */
262 { 93, 108, 114, 118, 121, 125, 128, 132, 136, 142, 158 }, /* alkaline */
263 { 103, 118, 121, 123, 124, 125, 126, 127, 128, 129, 135 } /* NiMH */
264 #elif CONFIG_BATTERY == BATT_LIION830
265 /* Toshiba Gigabeat Li Ion 830mAH figured from discharge curve */
266 { 348, 355, 359, 361, 363, 365, 370, 376, 380, 391, 399 },
267 #elif CONFIG_BATTERY == BATT_LIION750
268 /* Sansa Li Ion 750mAH FIXME this is a first linear approach */
269 { 330, 339, 348, 357, 366, 375, 384, 393, 402, 411, 420 },
270 #elif CONFIG_BATTERY == BATT_LIION400 /* iPOD Video 30GB */
271 /* iPOD Video 30GB Li-Ion 400mAh, first approach based upon measurements */
272 { 345, 367, 371, 375, 379, 383, 387, 393, 401, 410, 418 },
273 #elif CONFIG_BATTERY == BATT_LIION300
274 /* measured values */
275 { 323, 362, 370, 373, 375, 378, 383, 389, 395, 403, 416 },
276 #else /* NiMH */
277 /* original values were taken directly after charging, but it should show
278 100% after turning off the device for some hours, too */
279 { 450, 481, 491, 497, 503, 507, 512, 514, 517, 525, 540 }
280 /* orig. values: ...,528,560 */
281 #endif
284 #if CONFIG_CHARGING
285 /* voltages (centivolt) of 0%, 10%, ... 100% when charging enabled */
286 static const unsigned short percent_to_volt_charge[11] =
288 #if CONFIG_BATTERY == BATT_LIPOL1300
289 /* values measured over one full charging cycle */
290 354, 386, 393, 398, 400, 402, 404, 408, 413, 418, 423 /* LiPo */
291 #elif CONFIG_BATTERY == BATT_LIION300
292 /* measured values */
293 323, 362, 370, 373, 375, 378, 383, 389, 395, 403, 416
294 #elif CONFIG_BATTERY == BATT_LIION400
295 /* iPOD Video 30GB Li-Ion 400mAh, first approach based upon measurements */
296 345, 367, 371, 375, 379, 383, 387, 393, 401, 410, 418
297 #elif CONFIG_BATTERY == BATT_LIION750
298 /* Sansa Li Ion 750mAH FIXME*/
299 330, 339, 348, 357, 366, 375, 384, 393, 402, 411, 420
300 #elif CONFIG_BATTERY == BATT_LIION830
301 /* Toshiba Gigabeat Li Ion 830mAH */
302 348, 355, 359, 361, 363, 365, 370, 376, 380, 391, 399
303 #elif CONFIG_BATTERY == BATT_LPCS355385
304 /* iriver H10 20GB */
305 399, 403, 406, 408, 410, 412, 415, 418, 422, 426, 431
306 #elif CONFIG_BATTERY == BATT_BP009
307 /* iriver H10 5/6GB: Not yet calibrated */
308 388, 392, 396, 400, 406, 410, 415, 419, 424, 428, 433
309 #else
310 /* values guessed, see
311 http://www.seattlerobotics.org/encoder/200210/LiIon2.pdf until someone
312 measures voltages over a charging cycle */
313 476, 544, 551, 556, 561, 564, 566, 576, 582, 584, 585 /* NiMH */
314 #endif
316 #endif /* CONFIG_CHARGING */
318 #if CONFIG_CHARGING == CHARGING_CONTROL
319 int long_delta; /* long term delta battery voltage */
320 int short_delta; /* short term delta battery voltage */
321 bool disk_activity_last_cycle = false; /* flag set to aid charger time
322 * calculation */
323 char power_message[POWER_MESSAGE_LEN] = ""; /* message that's shown in
324 debug menu */
325 /* percentage at which charging
326 starts */
327 int powermgmt_last_cycle_startstop_min = 0; /* how many minutes ago was the
328 charging started or
329 stopped? */
330 int powermgmt_last_cycle_level = 0; /* which level had the
331 batteries at this time? */
332 int trickle_sec = 0; /* how many seconds should the
333 charger be enabled per
334 minute for trickle
335 charging? */
336 int pid_p = 0; /* PID proportional term */
337 int pid_i = 0; /* PID integral term */
338 #endif /* CONFIG_CHARGING == CHARGING_CONTROL */
341 * Average battery voltage and charger voltage, filtered via a digital
342 * exponential filter.
344 static unsigned int avgbat; /* average battery voltage (filtering) */
345 static unsigned int battery_centivolts;/* filtered battery voltage, centvolts */
346 #ifdef HAVE_CHARGE_CTRL
347 #define BATT_AVE_SAMPLES 32 /* filter constant / @ 2Hz sample rate */
348 #elif CONFIG_BATTERY == BATT_LIPOL1300
349 #define BATT_AVE_SAMPLES 128 /* slow filter for iriver */
350 #else
351 #define BATT_AVE_SAMPLES 64 /* medium filter constant for all others */
352 #endif
354 /* battery level (0-100%) of this minute, updated once per minute */
355 static int battery_percent = -1;
356 static int battery_capacity = BATTERY_CAPACITY_DEFAULT; /* default value, mAh */
357 static int battery_type = 0;
359 /* Power history: power_history[0] is the newest sample */
360 unsigned short power_history[POWER_HISTORY_LEN];
362 static char power_stack[DEFAULT_STACK_SIZE/2 + DEBUG_STACK];
363 static const char power_thread_name[] = "power";
365 static int poweroff_timeout = 0;
366 static int powermgmt_est_runningtime_min = -1;
368 static bool sleeptimer_active = false;
369 static long sleeptimer_endtick;
371 static long last_event_tick;
373 static int voltage_to_battery_level(int battery_centivolts);
374 static void battery_status_update(void);
375 static int runcurrent(void);
377 void battery_read_info(int *adc, int *voltage, int *level)
379 int adc_battery = adc_read(ADC_UNREG_POWER);
380 int centivolts = adc_battery*BATTERY_SCALE_FACTOR / 10000;
382 if (adc)
383 *adc = adc_battery;
385 if (voltage)
386 *voltage = centivolts;
388 if (level)
389 *level = voltage_to_battery_level(centivolts);
392 void reset_poweroff_timer(void)
394 last_event_tick = current_tick;
397 #if BATTERY_TYPES_COUNT > 1
398 void set_battery_type(int type)
400 if (type != battery_type) {
401 battery_type = type;
402 battery_status_update(); /* recalculate the battery status */
405 #endif
407 void set_battery_capacity(int capacity)
409 battery_capacity = capacity;
410 if (battery_capacity > BATTERY_CAPACITY_MAX)
411 battery_capacity = BATTERY_CAPACITY_MAX;
412 if (battery_capacity < BATTERY_CAPACITY_MIN)
413 battery_capacity = BATTERY_CAPACITY_MIN;
414 battery_status_update(); /* recalculate the battery status */
417 int battery_time(void)
419 return powermgmt_est_runningtime_min;
422 /* Returns battery level in percent */
423 int battery_level(void)
425 return battery_percent;
428 /* Returns filtered battery voltage [centivolts] */
429 unsigned int battery_voltage(void)
431 return battery_centivolts;
434 /* Returns battery voltage from ADC [centivolts] */
435 int battery_adc_voltage(void)
437 return (adc_read(ADC_UNREG_POWER) * BATTERY_SCALE_FACTOR + 5000) / 10000;
440 /* Tells if the battery level is safe for disk writes */
441 bool battery_level_safe(void)
443 return battery_centivolts > battery_level_dangerous[battery_type];
446 void set_poweroff_timeout(int timeout)
448 poweroff_timeout = timeout;
451 void set_sleep_timer(int seconds)
453 if(seconds) {
454 sleeptimer_active = true;
455 sleeptimer_endtick = current_tick + seconds * HZ;
457 else {
458 sleeptimer_active = false;
459 sleeptimer_endtick = 0;
463 int get_sleep_timer(void)
465 if(sleeptimer_active)
466 return (sleeptimer_endtick - current_tick) / HZ;
467 else
468 return 0;
471 /* look into the percent_to_volt_* table and get a realistic battery level */
472 static int voltage_to_percent(int voltage, const short* table)
474 if (voltage <= table[0])
475 return 0;
476 else
477 if (voltage >= table[10])
478 return 100;
479 else {
480 /* search nearest value */
481 int i = 0;
482 while ((i < 10) && (table[i+1] < voltage))
483 i++;
484 /* interpolate linear between the smaller and greater value */
485 return (i * 10) /* Tens digit, 10% per entry */
486 + (((voltage - table[i]) * 10)
487 / (table[i+1] - table[i])); /* Ones digit: interpolated */
491 /* update battery level and estimated runtime, called once per minute or
492 * when battery capacity / type settings are changed */
493 static int voltage_to_battery_level(int battery_centivolts)
495 int level;
497 #if defined(CONFIG_CHARGER) && CONFIG_BATTERY == BATT_LIPOL1300
498 if (charger_input_state == NO_CHARGER) {
499 /* discharging. calculate new battery level and average with last */
500 level = voltage_to_percent(battery_centivolts,
501 percent_to_volt_discharge[battery_type]);
502 if (level != (battery_percent - 1))
503 level = (level + battery_percent + 1) / 2;
505 else if (charger_input_state == CHARGER_UNPLUGGED) {
506 /* just unplugged. adjust filtered values */
507 battery_centivolts -= percent_to_volt_charge[battery_percent/10] -
508 percent_to_volt_discharge[0][battery_percent/10];
509 avgbat = battery_centivolts * 10000 * BATT_AVE_SAMPLES;
510 level = battery_percent;
512 else if (charger_input_state == CHARGER_PLUGGED) {
513 /* just plugged in. adjust battery values */
514 battery_centivolts += percent_to_volt_charge[battery_percent/10] -
515 percent_to_volt_discharge[0][battery_percent/10];
516 avgbat = battery_centivolts * 10000 * BATT_AVE_SAMPLES;
517 level = MIN(12 * battery_percent / 10, 99);
519 else { /* charging. calculate new battery level */
520 level = voltage_to_percent(battery_centivolts,
521 percent_to_volt_charge);
523 #elif CONFIG_CHARGING >= CHARGING_MONITOR
524 if (charge_state == DISCHARGING) {
525 level = voltage_to_percent(battery_centivolts,
526 percent_to_volt_discharge[battery_type]);
528 else if (charge_state == CHARGING) {
529 /* battery level is defined to be < 100% until charging is finished */
530 level = MIN(voltage_to_percent(battery_centivolts,
531 percent_to_volt_charge), 99);
533 else { /* in topoff/trickle charge, battery is by definition 100% full */
534 level = 100;
536 #else
537 /* always use the discharge table */
538 level = voltage_to_percent(battery_centivolts,
539 percent_to_volt_discharge[battery_type]);
540 #endif
542 return level;
545 static void battery_status_update(void)
547 int level = voltage_to_battery_level(battery_centivolts);
550 /* calculate estimated remaining running time */
551 /* discharging: remaining running time */
552 /* charging: remaining charging time */
553 #if CONFIG_CHARGING >= CHARGING_MONITOR
554 if (charge_state == CHARGING) {
555 powermgmt_est_runningtime_min = (100 - level) * battery_capacity * 60
556 / 100 / (CURRENT_MAX_CHG - runcurrent());
558 else
559 #elif CONFIG_CHARGING && CONFIG_BATTERY == BATT_LIPOL1300
560 if (charger_inserted()) {
561 #ifdef IRIVER_H300_SERIES
562 /* H300_SERIES use CURRENT_MAX_CHG for basic charge time (80%)
563 * plus 110 min top off charge time */
564 powermgmt_est_runningtime_min = ((100-level) * battery_capacity * 80
565 /100 / CURRENT_MAX_CHG) + 110;
566 #else
567 /* H100_SERIES scaled for 160 min basic charge time (80%) on
568 * 1600 mAh battery plus 110 min top off charge time */
569 powermgmt_est_runningtime_min = ((100 - level) * battery_capacity
570 / 993) + 110;
571 #endif
572 level = (level * 80) / 100;
573 if (level > 72) { /* > 91% */
574 int i = POWER_HISTORY_LEN;
575 int d = 1;
576 #ifdef HAVE_CHARGE_STATE
577 if (charge_state == DISCHARGING)
578 d = -2;
579 #endif
580 while ((i > 2) && (d > 0)) /* search zero or neg. delta */
581 d = power_history[0] - power_history[--i];
582 if ((((d == 0) && (i > 6)) || (d == -1)) && (i < 118)) {
583 /* top off charging */
584 level = MIN(80 + (i*19 / 113), 99); /* show 81% .. 99% */
585 powermgmt_est_runningtime_min = MAX(116 - i, 0);
587 else if ((d < 0) || (i > 117)) {
588 /* charging finished */
589 level = 100;
590 powermgmt_est_runningtime_min = battery_capacity * 60
591 / runcurrent();
595 else
596 #endif /* BATT_LIPOL1300 */
598 if ((battery_centivolts + 2) > percent_to_volt_discharge[0][0])
599 powermgmt_est_runningtime_min = (level + battery_percent) * 60 *
600 battery_capacity / 200 / runcurrent();
601 else
602 powermgmt_est_runningtime_min = (battery_centivolts -
603 battery_level_shutoff[0]) / 2;
606 battery_percent = level;
610 * We shut off in the following cases:
611 * 1) The unit is idle, not playing music
612 * 2) The unit is playing music, but is paused
613 * 3) The battery level has reached shutdown limit
615 * We do not shut off in the following cases:
616 * 1) The USB is connected
617 * 2) The charger is connected
618 * 3) We are recording, or recording with pause
619 * 4) The radio is playing
621 static void handle_auto_poweroff(void)
623 long timeout = poweroff_idle_timeout_value[poweroff_timeout]*60*HZ;
624 int audio_stat = audio_status();
626 #if CONFIG_CHARGING
628 * Inhibit shutdown as long as the charger is plugged in. If it is
629 * unplugged, wait for a timeout period and then shut down.
631 if(charger_input_state == CHARGER || audio_stat == AUDIO_STATUS_PLAY) {
632 last_event_tick = current_tick;
634 #endif
636 /* switch off unit if battery level is too low for reliable operation */
637 #if (CONFIG_BATTERY!=BATT_4AA_NIMH) && (CONFIG_BATTERY!=BATT_3AAA)&& \
638 (CONFIG_BATTERY!=BATT_1AA)
639 if(battery_centivolts < battery_level_shutoff[battery_type]) {
640 if(!shutdown_timeout) {
641 backlight_on();
642 sys_poweroff();
645 #endif
647 if(timeout &&
648 #if CONFIG_TUNER && !defined(BOOTLOADER)
649 (!(get_radio_status() & FMRADIO_PLAYING)) &&
650 #endif
651 !usb_inserted() &&
652 ((audio_stat == 0) ||
653 ((audio_stat == (AUDIO_STATUS_PLAY | AUDIO_STATUS_PAUSE)) &&
654 !sleeptimer_active)))
656 if(TIME_AFTER(current_tick, last_event_tick + timeout) &&
657 TIME_AFTER(current_tick, last_disk_activity + timeout))
659 sys_poweroff();
662 else
664 /* Handle sleeptimer */
665 if(sleeptimer_active && !usb_inserted())
667 if(TIME_AFTER(current_tick, sleeptimer_endtick))
669 audio_stop();
670 #if CONFIG_CHARGING && !defined(HAVE_POWEROFF_WHILE_CHARGING)
671 if((charger_input_state == CHARGER) ||
672 (charger_input_state == CHARGER_PLUGGED))
674 DEBUGF("Sleep timer timeout. Stopping...\n");
675 set_sleep_timer(0);
676 backlight_off(); /* Nighty, nighty... */
678 else
679 #endif
681 DEBUGF("Sleep timer timeout. Shutting off...\n");
682 sys_poweroff();
690 * Estimate how much current we are drawing just to run.
692 static int runcurrent(void)
694 int current;
696 #if MEM == 8 && !defined(HAVE_MMC)
697 /* assuming 192 kbps, the running time is 22% longer with 8MB */
698 current = (CURRENT_NORMAL*100/122);
699 #else
700 current = CURRENT_NORMAL;
701 #endif /* MEM == 8 */
703 if(usb_inserted()
704 #if defined(HAVE_USB_POWER)
705 #if (CURRENT_USB < CURRENT_NORMAL)
706 || usb_powered()
707 #else
708 && !usb_powered()
709 #endif
710 #endif
713 current = CURRENT_USB;
716 #if defined(HAVE_BACKLIGHT) && !defined(BOOTLOADER)
717 if (backlight_get_current_timeout() == 0) /* LED always on */
718 current += CURRENT_BACKLIGHT;
719 #endif
721 #if defined(HAVE_RECORDING) && defined(CURRENT_RECORD)
722 if (audio_status() & AUDIO_STATUS_RECORD)
723 current += CURRENT_RECORD;
724 #endif
726 #ifdef HAVE_SPDIF_POWER
727 if (spdif_powered())
728 current += CURRENT_SPDIF_OUT;
729 #endif
731 #ifdef HAVE_REMOTE_LCD
732 if (remote_detect())
733 current += CURRENT_REMOTE;
734 #endif
736 return(current);
740 /* Check to see whether or not we've received an alarm in the last second */
741 #ifdef HAVE_RTC_ALARM
742 static void power_thread_rtc_process(void)
744 if (rtc_check_alarm_flag()) {
745 rtc_enable_alarm(false);
748 #endif
751 * This function is called to do the relativly long sleep waits from within the
752 * main power_thread loop while at the same time servicing any other periodic
753 * functions in the power thread which need to be called at a faster periodic
754 * rate than the slow periodic rate of the main power_thread loop.
756 * While we are waiting for the time to expire, we average the battery
757 * voltages.
759 static void power_thread_sleep(int ticks)
761 int small_ticks;
763 while (ticks > 0) {
765 #if CONFIG_CHARGING
767 * Detect charger plugged/unplugged transitions. On a plugged or
768 * unplugged event, we return immediately, run once through the main
769 * loop (including the subroutines), and end up back here where we
770 * transition to the appropriate steady state charger on/off state.
772 if(charger_inserted()
773 #ifdef HAVE_USB_POWER /* USB powered or USB inserted both provide power */
774 || usb_powered()
775 #if CONFIG_CHARGING
776 || (usb_inserted() && usb_charging_enabled())
777 #endif
778 #endif
780 switch(charger_input_state) {
781 case NO_CHARGER:
782 case CHARGER_UNPLUGGED:
783 charger_input_state = CHARGER_PLUGGED;
784 return;
785 case CHARGER_PLUGGED:
786 queue_broadcast(SYS_CHARGER_CONNECTED, 0);
787 charger_input_state = CHARGER;
788 break;
789 case CHARGER:
790 break;
792 } else { /* charger not inserted */
793 switch(charger_input_state) {
794 case NO_CHARGER:
795 break;
796 case CHARGER_UNPLUGGED:
797 queue_broadcast(SYS_CHARGER_DISCONNECTED, 0);
798 charger_input_state = NO_CHARGER;
799 break;
800 case CHARGER_PLUGGED:
801 case CHARGER:
802 charger_input_state = CHARGER_UNPLUGGED;
803 return;
806 #endif
807 #if CONFIG_CHARGING == CHARGING_MONITOR
808 switch (charger_input_state) {
809 case CHARGER_UNPLUGGED:
810 case NO_CHARGER:
811 charge_state = DISCHARGING;
812 break;
813 case CHARGER_PLUGGED:
814 case CHARGER:
815 if (charging_state()) {
816 charge_state = CHARGING;
817 } else {
818 charge_state = DISCHARGING;
820 break;
823 #endif /* CONFIG_CHARGING == CHARGING_MONITOR */
825 small_ticks = MIN(HZ/2, ticks);
826 sleep(small_ticks);
827 ticks -= small_ticks;
829 /* If the power off timeout expires, the main thread has failed
830 to shut down the system, and we need to force a power off */
831 if(shutdown_timeout) {
832 shutdown_timeout -= small_ticks;
833 if(shutdown_timeout <= 0)
834 power_off();
837 #ifdef HAVE_RTC_ALARM
838 power_thread_rtc_process();
839 #endif
842 * Do a digital exponential filter. We don't sample the battery if
843 * the disk is spinning unless we are in USB mode (the disk will most
844 * likely always be spinning in USB mode).
846 if (!ata_disk_is_active() || usb_inserted()) {
847 avgbat += adc_read(ADC_UNREG_POWER) * BATTERY_SCALE_FACTOR
848 - (avgbat / BATT_AVE_SAMPLES);
850 * battery_centivolts is the centivolt-scaled filtered battery value.
852 battery_centivolts = (avgbat / BATT_AVE_SAMPLES + 5000) / 10000;
854 /* update battery status every time an update is available */
855 battery_status_update();
857 else if (battery_percent < 8) {
858 /* If battery is low, observe voltage during disk activity.
859 * Shut down if voltage drops below shutoff level and we are not
860 * using NiMH or Alkaline batteries.
862 battery_centivolts = (battery_adc_voltage() +
863 battery_centivolts + 1) / 2;
865 /* update battery status every time an update is available */
866 battery_status_update();
868 #if (CONFIG_BATTERY!=BATT_4AA_NIMH) && (CONFIG_BATTERY!=BATT_3AAA)&& \
869 (CONFIG_BATTERY!=BATT_1AA)
870 if (!shutdown_timeout &&
871 (battery_centivolts < battery_level_shutoff[battery_type]))
872 sys_poweroff();
873 else
874 #endif
875 avgbat += battery_centivolts * 10000
876 - (avgbat / BATT_AVE_SAMPLES);
879 #if CONFIG_CHARGING == CHARGING_CONTROL
880 if (ata_disk_is_active()) {
881 /* flag hdd use for charging calculation */
882 disk_activity_last_cycle = true;
884 #endif
885 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
887 * If we have a lot of pending writes or if the disk is spining,
888 * fsync the debug log file.
890 if((wrcount > 10) || ((wrcount > 0) && ata_disk_is_active())) {
891 fsync(fd);
892 wrcount = 0;
894 #endif
900 * This power thread maintains a history of battery voltage
901 * and implements a charging algorithm.
902 * For a complete description of the charging algorithm read
903 * docs/CHARGING_ALGORITHM.
906 static void power_thread(void)
908 int i;
909 short *phps, *phpd; /* power history rotation pointers */
910 #if CONFIG_CHARGING == CHARGING_CONTROL
911 unsigned int target_voltage = TRICKLE_VOLTAGE; /* desired topoff/trickle
912 * voltage level */
913 int charge_max_time_idle = 0; /* max. charging duration, calculated at
914 * beginning of charging */
915 int charge_max_time_now = 0; /* max. charging duration including
916 * hdd activity */
917 int minutes_disk_activity = 0; /* count minutes of hdd use during
918 * charging */
919 int last_disk_activity = CHARGE_END_LONGD + 1; /* last hdd use x mins ago */
920 #endif
922 /* initialize the voltages for the exponential filter */
923 avgbat = adc_read(ADC_UNREG_POWER) * BATTERY_SCALE_FACTOR + 15000;
925 #ifndef HAVE_MMC /* this adjustment is only needed for HD based */
926 /* The battery voltage is usually a little lower directly after
927 turning on, because the disk was used heavily. Raise it by 5% */
928 #ifdef HAVE_CHARGING
929 if(!charger_inserted()) /* only if charger not connected */
930 #endif
931 avgbat += (percent_to_volt_discharge[battery_type][6] -
932 percent_to_volt_discharge[battery_type][5]) * 5000;
933 #endif /* not HAVE_MMC */
935 avgbat = avgbat * BATT_AVE_SAMPLES;
936 battery_centivolts = avgbat / BATT_AVE_SAMPLES / 10000;
938 #if CONFIG_CHARGING
939 if(charger_inserted()) {
940 battery_percent = voltage_to_percent(battery_centivolts,
941 percent_to_volt_charge);
942 #if CONFIG_BATTERY == BATT_LIPOL1300
943 charger_input_state = CHARGER;
944 #endif
945 } else
946 #endif
947 { battery_percent = voltage_to_percent(battery_centivolts,
948 percent_to_volt_discharge[battery_type]);
949 battery_percent += (battery_percent < 100);
952 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
953 fd = -1;
954 wrcount = 0;
955 #endif
957 while (1)
959 /* rotate the power history */
960 phpd = &power_history[POWER_HISTORY_LEN - 1];
961 phps = phpd - 1;
962 for (i = 0; i < POWER_HISTORY_LEN-1; i++)
963 *phpd-- = *phps--;
965 /* insert new value at the start, in centivolts 8-) */
966 power_history[0] = battery_centivolts;
968 #if CONFIG_CHARGING == CHARGING_CONTROL
969 if (charger_input_state == CHARGER_PLUGGED) {
970 pid_p = 0;
971 pid_i = 0;
972 snprintf(power_message, POWER_MESSAGE_LEN, "Charger plugged in");
974 * The charger was just plugged in. If the battery level is
975 * nearly charged, just trickle. If the battery is low, start
976 * a full charge cycle. If the battery level is in between,
977 * top-off and then trickle.
979 if(battery_percent > START_TOPOFF_CHG) {
980 powermgmt_last_cycle_level = battery_percent;
981 powermgmt_last_cycle_startstop_min = 0;
982 if(battery_percent >= START_TRICKLE_CHG) {
983 charge_state = TRICKLE;
984 target_voltage = TRICKLE_VOLTAGE;
985 } else {
986 charge_state = TOPOFF;
987 target_voltage = TOPOFF_VOLTAGE;
989 } else {
991 * Start the charger full strength
993 i = CHARGE_MAX_TIME_1500 * battery_capacity / 1500;
994 charge_max_time_idle =
995 i * (100 + 35 - battery_percent) / 100;
996 if (charge_max_time_idle > i) {
997 charge_max_time_idle = i;
999 charge_max_time_now = charge_max_time_idle;
1001 snprintf(power_message, POWER_MESSAGE_LEN,
1002 "ChgAt %d%% max %dm", battery_level(),
1003 charge_max_time_now);
1005 /* enable the charger after the max time calc is done,
1006 because battery_level depends on if the charger is
1007 on */
1008 DEBUGF("power: charger inserted and battery"
1009 " not full, charging\n");
1010 powermgmt_last_cycle_level = battery_percent;
1011 powermgmt_last_cycle_startstop_min = 0;
1012 trickle_sec = 60;
1013 long_delta = short_delta = 999999;
1014 charge_state = CHARGING;
1017 if (charge_state == CHARGING) {
1018 /* alter charge time max length with extra disk use */
1019 if (disk_activity_last_cycle) {
1020 minutes_disk_activity++;
1021 charge_max_time_now = charge_max_time_idle +
1022 (minutes_disk_activity * 2 / 5);
1023 disk_activity_last_cycle = false;
1024 last_disk_activity = 0;
1025 } else {
1026 last_disk_activity++;
1029 * Check the delta voltage over the last X minutes so we can do
1030 * our end-of-charge logic based on the battery level change.
1031 *(no longer use minimum time as logic for charge end has 50
1032 * minutes minimum charge built in)
1034 if (powermgmt_last_cycle_startstop_min > CHARGE_END_SHORTD) {
1035 short_delta = power_history[0] -
1036 power_history[CHARGE_END_SHORTD - 1];
1039 if (powermgmt_last_cycle_startstop_min > CHARGE_END_LONGD) {
1041 * Scan the history: the points where measurement is taken need to
1042 * be fairly static. (check prior to short delta 'area')
1043 * (also only check first and last 10 cycles - delta in middle OK)
1045 long_delta = power_history[0] -
1046 power_history[CHARGE_END_LONGD - 1];
1048 for(i = CHARGE_END_SHORTD; i < CHARGE_END_SHORTD + 10; i++) {
1049 if(((power_history[i] - power_history[i+1]) > 5) ||
1050 ((power_history[i] - power_history[i+1]) < -5)) {
1051 long_delta = 777777;
1052 break;
1055 for(i = CHARGE_END_LONGD - 11; i < CHARGE_END_LONGD - 1 ; i++) {
1056 if(((power_history[i] - power_history[i+1]) > 5) ||
1057 ((power_history[i] - power_history[i+1]) < -5)) {
1058 long_delta = 888888;
1059 break;
1064 snprintf(power_message, POWER_MESSAGE_LEN,
1065 "Chg %dm, max %dm", powermgmt_last_cycle_startstop_min,
1066 charge_max_time_now);
1068 * End of charge criteria (any qualify):
1069 * 1) Charged a long time
1070 * 2) DeltaV went negative for a short time ( & long delta static)
1071 * 3) DeltaV was negative over a longer period (no disk use only)
1072 * Note: short_delta and long_delta are centivolts
1074 if ((powermgmt_last_cycle_startstop_min >= charge_max_time_now) ||
1075 (short_delta <= -5 && long_delta < 5 ) || (long_delta < -2 &&
1076 last_disk_activity > CHARGE_END_LONGD)) {
1077 if (powermgmt_last_cycle_startstop_min > charge_max_time_now) {
1078 DEBUGF("power: powermgmt_last_cycle_startstop_min > charge_max_time_now, "
1079 "enough!\n");
1081 *have charged too long and deltaV detection did not
1082 *work!
1084 snprintf(power_message, POWER_MESSAGE_LEN,
1085 "Chg tmout %d min", charge_max_time_now);
1087 * Switch to trickle charging. We skip the top-off
1088 * since we've effectively done the top-off operation
1089 * already since we charged for the maximum full
1090 * charge time.
1092 powermgmt_last_cycle_level = battery_percent;
1093 powermgmt_last_cycle_startstop_min = 0;
1094 charge_state = TRICKLE;
1097 * set trickle charge target to a relative voltage instead
1098 * of an arbitrary value - the fully charged voltage may
1099 * vary according to ambient temp, battery condition etc
1100 * trickle target is -0.15v from full voltage acheived
1101 * topup target is -0.05v from full voltage
1103 target_voltage = power_history[0] - 15;
1105 } else {
1106 if(short_delta <= -5) {
1107 DEBUGF("power: short-term negative"
1108 " delta, enough!\n");
1109 snprintf(power_message, POWER_MESSAGE_LEN,
1110 "end negd %d %dmin", short_delta,
1111 powermgmt_last_cycle_startstop_min);
1112 target_voltage = power_history[CHARGE_END_SHORTD - 1]
1113 - 5;
1114 } else {
1115 DEBUGF("power: long-term small "
1116 "positive delta, enough!\n");
1117 snprintf(power_message, POWER_MESSAGE_LEN,
1118 "end lowd %d %dmin", long_delta,
1119 powermgmt_last_cycle_startstop_min);
1120 target_voltage = power_history[CHARGE_END_LONGD - 1]
1121 - 5;
1124 * Switch to top-off charging.
1126 powermgmt_last_cycle_level = battery_percent;
1127 powermgmt_last_cycle_startstop_min = 0;
1128 charge_state = TOPOFF;
1132 else if (charge_state != DISCHARGING) /* top off or trickle */
1135 *Time to switch from topoff to trickle?
1137 if ((charge_state == TOPOFF) &&
1138 (powermgmt_last_cycle_startstop_min > TOPOFF_MAX_TIME))
1140 powermgmt_last_cycle_level = battery_percent;
1141 powermgmt_last_cycle_startstop_min = 0;
1142 charge_state = TRICKLE;
1143 target_voltage = target_voltage - 10;
1146 * Adjust trickle charge time (proportional and integral terms).
1147 * Note: I considered setting the level higher if the USB is
1148 * plugged in, but it doesn't appear to be necessary and will
1149 * generate more heat [gvb].
1152 pid_p = target_voltage - battery_centivolts;
1153 if((pid_p > PID_DEADZONE) || (pid_p < -PID_DEADZONE))
1154 pid_p = pid_p * PID_PCONST;
1155 else
1156 pid_p = 0;
1157 if((unsigned) battery_centivolts < target_voltage) {
1158 if(pid_i < 60) {
1159 pid_i++; /* limit so it doesn't "wind up" */
1161 } else {
1162 if(pid_i > 0) {
1163 pid_i--; /* limit so it doesn't "wind up" */
1167 trickle_sec = pid_p + pid_i;
1169 if(trickle_sec > 60) {
1170 trickle_sec = 60;
1172 if(trickle_sec < 0) {
1173 trickle_sec = 0;
1176 } else if (charge_state == DISCHARGING) {
1177 trickle_sec = 0;
1179 * The charger is enabled here only in one case: if it was
1180 * turned on at boot time (power_init). Turn it off now.
1182 if (charger_enabled)
1183 charger_enable(false);
1186 if (charger_input_state == CHARGER_UNPLUGGED) {
1188 * The charger was just unplugged.
1190 DEBUGF("power: charger disconnected, disabling\n");
1192 charger_enable(false);
1193 powermgmt_last_cycle_level = battery_percent;
1194 powermgmt_last_cycle_startstop_min = 0;
1195 trickle_sec = 0;
1196 pid_p = 0;
1197 pid_i = 0;
1198 charge_state = DISCHARGING;
1199 snprintf(power_message, POWER_MESSAGE_LEN, "Charger: discharge");
1202 #endif /* CONFIG_CHARGING == CHARGING_CONTROL */
1204 /* sleep for a minute */
1206 #if CONFIG_CHARGING == CHARGING_CONTROL
1207 if(trickle_sec > 0) {
1208 charger_enable(true);
1209 power_thread_sleep(HZ * trickle_sec);
1211 if(trickle_sec < 60)
1212 charger_enable(false);
1213 power_thread_sleep(HZ * (60 - trickle_sec));
1214 #else
1215 power_thread_sleep(HZ * 60);
1216 #endif
1218 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1219 if(usb_inserted()) {
1220 if(fd >= 0) {
1221 /* It is probably too late to close the file but we can try...*/
1222 close(fd);
1223 fd = -1;
1225 } else {
1226 if(fd < 0) {
1227 fd = open(DEBUG_FILE_NAME, O_WRONLY | O_APPEND | O_CREAT);
1228 if(fd >= 0) {
1229 snprintf(debug_message, DEBUG_MESSAGE_LEN,
1230 "cycle_min, bat_centivolts, bat_percent, chgr_state, charge_state, pid_p, pid_i, trickle_sec\n");
1231 write(fd, debug_message, strlen(debug_message));
1232 wrcount = 99; /* force a flush */
1235 if(fd >= 0) {
1236 snprintf(debug_message, DEBUG_MESSAGE_LEN,
1237 "%d, %d, %d, %d, %d, %d, %d, %d\n",
1238 powermgmt_last_cycle_startstop_min, battery_centivolts,
1239 battery_percent, charger_input_state, charge_state,
1240 pid_p, pid_i, trickle_sec);
1241 write(fd, debug_message, strlen(debug_message));
1242 wrcount++;
1245 #endif
1246 handle_auto_poweroff();
1248 #if CONFIG_CHARGING == CHARGING_CONTROL
1249 powermgmt_last_cycle_startstop_min++;
1250 #endif
1254 void powermgmt_init(void)
1256 /* init history to 0 */
1257 memset(power_history, 0x00, sizeof(power_history));
1258 create_thread(power_thread, power_stack, sizeof(power_stack),
1259 power_thread_name IF_PRIO(, PRIORITY_SYSTEM)
1260 IF_COP(, CPU, false));
1263 #endif /* SIMULATOR */
1265 void sys_poweroff(void)
1267 logf("sys_poweroff()");
1268 /* If the main thread fails to shut down the system, we will force a
1269 power off after an 20 second timeout - 28 seconds if recording */
1270 if (shutdown_timeout == 0)
1272 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1273 pcf50606_reset_timeout(); /* Reset timer on first attempt only */
1274 #endif
1275 #ifdef HAVE_RECORDING
1276 if (audio_status() & AUDIO_STATUS_RECORD)
1277 shutdown_timeout += HZ*8;
1278 #endif
1279 shutdown_timeout += HZ*20;
1282 queue_broadcast(SYS_POWEROFF, 0);
1285 void cancel_shutdown(void)
1287 logf("sys_cancel_shutdown()");
1289 #if (defined(IAUDIO_X5) || defined(IAUDIO_M5)) && !defined (SIMULATOR)
1290 /* TODO: Move some things to target/ tree */
1291 if (shutdown_timeout)
1292 pcf50606_reset_timeout();
1293 #endif
1295 shutdown_timeout = 0;
1298 /* Various hardware housekeeping tasks relating to shutting down the jukebox */
1299 void shutdown_hw(void)
1301 #ifndef SIMULATOR
1302 #if defined(DEBUG_FILE) && (CONFIG_CHARGING == CHARGING_CONTROL)
1303 if(fd >= 0) {
1304 close(fd);
1305 fd = -1;
1307 #endif
1308 audio_stop();
1309 if (battery_level_safe()) { /* do not save on critical battery */
1310 #ifdef HAVE_LCD_BITMAP
1311 glyph_cache_save();
1312 #endif
1313 if(ata_disk_is_active())
1314 ata_spindown(1);
1316 while(ata_disk_is_active())
1317 sleep(HZ/10);
1319 #if CONFIG_CODEC != SWCODEC
1320 mp3_shutdown();
1321 #else
1322 audiohw_close();
1323 #endif
1325 /* If HD is still active we try to wait for spindown, otherwise the
1326 shutdown_timeout in power_thread_sleep will force a power off */
1327 while(ata_disk_is_active())
1328 sleep(HZ/10);
1329 #ifndef IAUDIO_X5
1330 lcd_set_contrast(0);
1331 #endif /* IAUDIO_X5 */
1332 #ifdef HAVE_REMOTE_LCD
1333 lcd_remote_set_contrast(0);
1334 #endif
1336 /* Small delay to make sure all HW gets time to flush. Especially
1337 eeprom chips are quite slow and might be still writing the last
1338 byte. */
1339 sleep(HZ/4);
1340 power_off();
1341 #endif /* #ifndef SIMULATOR */