pax_global_header00006660000000000000000000000064130133054250014506gustar00rootroot0000000000000052 comment=7a1963c88eee376d94793c239d9d69b885f38b96 battery-stats-0.5.6/000077500000000000000000000000001301330542500143245ustar00rootroot00000000000000battery-stats-0.5.6/.gitignore000066400000000000000000000004001301330542500163060ustar00rootroot00000000000000# KDevelop *.kdev4 # Autotools /autom4te.cache /stamp-h1 Makefile /config.status /config.log /config.h /aclocal.m4 Makefile.in /config/ /config.h.in /configure .deps # General *.orig *~ /build*/ # from git merge *.BACKUP.* *.BASE.* *.LOCAL.* *.REMOTE.* battery-stats-0.5.6/CHANGES.md000066400000000000000000000111121301330542500157120ustar00rootroot000000000000000.5.6 (2016-11-17) ===== * Corrected links in README. * Extended battery-stats-collector to handle Purism Librem-13 (ADP1). * Adjusted udev rules to really trigger on power changes. * Adjusted battery-graph.in to avoid syntax error when no discharging is logged yet. 0.5.5 (2016-06-14) ===== * Disable rate calculations in battery-graph when there is no data yet. * Make sure battery-stats-collector do not fail when no battery is present, allowing hibernation to happen. 0.5.4 (2016-05-22) ===== * Fix typos breaking battery-graph. * Get battery-stats-graph working when selected from the desktop file. 0.5.3 (2016-05-22) ===== * Fixed some typos in the documentation. * Added keywords to desktop files. * Stopped installing non-working battery-stats-graph-gnuplot until it is fixed or we decide to drop it. * Adjusted battery-log to report log files sorted on file timestamp. * Made battery-stats-collector able to handle more types of hardware where AC is named ACAD. * Added linear fit and colors to output from battery-graph script. 0.5.2 (2016-03-29) ===== * Extended battery-stats-collector to handle batteries with charge_* instead of energy_* values. * Changed battery-stats-graph to read from /var/log/battery-stats.csv* instead of stdin by default. * Changed battery-stats-graph to handle files less fields than currently is currently collected by collect-csv. * Changed battery-stats-graph-flow to graph using lines instead of dots to make the flow information easier to see. * Changed collect-csv to handle BAT* symlinks in /sys/class/power_supply/. 0.5.1 (2016-03-23) ===== * Added udev rule to call collector when power status changes. * Fixed battery-stats-graph-flow to work with new file name and format. * Fixed typo in desktop file blocking the entry from showing the graph. * Changed collection frequence for original collector from 30 seconds to 10 minutes, and call collector when power and suspend status change instead. 0.5.0 (2016-03-22) ===== * Added scripts to collect more battery statistics as a CSV file on power related events (like AC power connect/disconnect and into/out of sleep and hibernation). * New desktop file to graph CSV file using the python script battery-stats-graph. 0.4.0 (2016-03-14) ===== * New developer. * Collector rewritten as shell script, losing some features along the way. 0.3.7 (unreleased) ===== * Use CMake buildsystem, and other code base cleanups * Make Gnuplot syntax used in graph-setup compatible with gnuplot-4.6 * Fix missing 'I' option in help output * Make it possible to write to stdout instead just /var/log/... * Convert all source files to UTF-8 * Improve --help output a lot 0.3.6 (2009-09-19) ===== * New upstream release that integrates a patch to specify the battery number (see http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=535815) 0.3.5 (2009-06-13) ===== * Debian release 0.3.4 (2009-01-25) ===== * Merged ACPI support from debian/patches - initial patch author: Michael Bunk - patch adapted to support autotools by Antonio Radici * Created a ./configure script using autotools to support the optional ACPI patch * New gnuplot syntax supported, taken from debian/patches * Corrected some manpages formatting error, taken from debian/patches * New maintaner: Antonio Radici * Added an icon, gnome-ccperiph.png, it's taken from the debian package gnome-desktop-data, the icon is licensed with the GPL-2 and it's copyrighted by the GNOME group 0.3.3 (2003-03-21) ===== * Converted part of the CVS changelog into this. The debian/changelog is exclusively for use by debian-specific changes from now on. * battery-log: Added (a slightly modified version of) patch from David Z Maze (debian bug #185623). * battery-stats-collector.c:myversion : oops: This still thought it was version 0.2. It's now version 0.3.3... 0.3.2 (2003-02-21) ===== * debian/: README, changelog, control, copyright, init.d, logrotate, menu, rules: Removed debian-specific files from trunc. They now belong on the debian_version_xxx branches * debian/control: Slight paraphrasing in Note: * debian/changelog, debian/control: Bumped Standards-Version: to 3.5.6.1 * debian/README: No more mention of splitting into multiple packages - this is already mentioned in ../README * README: Slightly more verbose now * README: Bumped version number to 0.3.2 * debian/README: Now available on non-i386 too. * debian/: changelog, menu: Menu entry is now immune to log rotation * debian/changelog: No longer a debian-native package 0.3.1 (2003-01-16) ===== * See debian/changelog for prehistoric change history. battery-stats-0.5.6/CMakeLists.txt000066400000000000000000000007201301330542500170630ustar00rootroot00000000000000project(battery-stats) cmake_minimum_required(VERSION 2.6) include(CheckIncludeFiles) set(VERSION_STRING 0.4.0) set(INSTALL_TARGETS_DEFAULT_ARGS RUNTIME DESTINATION bin LIBRARY DESTINATION ${LIB_INSTALL_DIR} ARCHIVE DESTINATION ${LIB_INSTALL_DIR} COMPONENT Devel ) set(DATA_DIR "share/battery-stats") configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/config.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config.h ) add_subdirectory(data) add_subdirectory(src) battery-stats-0.5.6/COPYING000066400000000000000000000431101301330542500153560ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. battery-stats-0.5.6/README.md000066400000000000000000000122411301330542500156030ustar00rootroot00000000000000 __^__ __^__ ( ___ )---------------( ___ ) | / | battery-stats | \ | |___| |___| (_____)---------------(_____) Copyright (C) 2003 Karl E. Jørgensen Copyright (C) 2012 Kevin Funk Licensed under the GNU General Public License v2 Copyright (C) 2015 F Zenke Copyright (C) 2016 Petter Reinholdtsen What is it? =========== Battery-stats is a simple utility for collecting statistics about the laptop battery charge. Basically it will query ACPI at regular intervals and write the results to a log file. It also contains a simple plotting utility to show the battery charge over time. It does not (and will never) contain any graphical real-time "monitors" to show the current state of the battery; lots of other utilities already do this quite nicely. Interpreting the Stats ====================== First of all, I have no delusions of being a battery expert. This means that I will not make any serious attempt at interpreting the stats. What I know can be summed up as: When batteries age, they will take longer and longer to recharge, and will discharge quicker and quicker. However, I suspect that the *shape* of the charge/discarge curves (and the way the shape changes over several months) can tell something about the battery health. Ultimately, it should be possible to figure out when the battery will wear out and need replacement. Hopefully somebody with some electrochemical knowledge can fill in the (large) gaps of my knowledge here - I promise to give credit where credit is due. Note that several sorts of bugs can result in incorrect statistics. Such bugs can be introduced in several ways: * There are different ways of measuring "how full" a battery is. Apparently, it can be measured by the charging current. Such a measurement has to be "calibrated" with knowledge of the battery type (NiCad, LiIon etc), number of cells etc. * Buggy ACPI bios'es. * Buggy kernel ACPI. This I have not yet encountered, but in theory it exists... It is best to make sure that you actually have ACPI available from the kernel - and enabled at boot time. * Bugs in this software. But that's really, really improbable ;-) How this all started ==================== As a laptop user, I found myself with ageing batteries. And my (buggy) APM bios was far from accurate when it came to estimating how long I could run before having to recharge. I found other utilities out there that could help here - e.g. ibam @ ibam.sourceforge.net. These seem to work quite well with estimating how long before the next recharge. Short-term stuff. But none of them could tell me how the battery would perform over longer periods - weeks & months. Even with this tool, I don't have much of an idea (!), but at least this will make it possible for others to collect and interpret the statistics. Besides, being a typical laptop user, I did not have a "feel" for how long I *ought* to be able to go before a recharge - or how it had behaved in the past. I needed statistics, graphs, software and my name in lights. So I wrote this. Getting it ========== It is available for download at: https://github.com/petterreinholdtsen/battery-stats Compiling it ============ You will need: * The sources * CMake * GNU make Installing it ============= Debian ------ Debian unstable and wheezy have a package available: apt-get install battery-stats Installing from source ---------------------- - Make sure that you have bash installed - Make sure that you have gnuplot installed (only needed if you actually want graphs) - $ cmake .; make install To start the battery-stats-collector daemon at boot time, you will need to set up an init script and the relevant links /etc/rc*.d directories. This is all ready out-of-the-box for the Debian distribution. To access the graph plotter from the X desktop you will need to set up a menu item or launcher to launch /usr/bin/battery-graph. This is already set up for the Debian distribution. There are no provisions for stopping the log file from growing too much (unless you are running ... yes! you guessed it: Debian GNU/Linux!). Use of logrotate is recommended. Copyright ========= Please see the COPYING file in this directory. Bugs ==== None yet! Please report any bugs you find to: https://github.com/petterreinholdtsen/battery-stats Bugs related to the debian package should be reported to: http://bugs.debian.org/battery-stats Warranty ======== Sorry for the legalese blurb. Quick summary: "CMA" ... THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHOR(S) OR ANY DISTRIBUTORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. battery-stats-0.5.6/TODO000066400000000000000000000030661301330542500150210ustar00rootroot00000000000000This file describes bugs that I intend to fix and other things I want to do to battery-stats. Please don't report bugs which are already mentioned in here, unless you can add more information - or even better: a patch. Different colours on the graph depending on battery state ========================================================= [Suggested by Werner Heuser ] It would be nice if the graph had one colour when the battery was charging, and another colour when it was discarging. Battery-graph options for graphs ================================ By default, battery-graph will plot the percentage charge of the battery. It would be nice to have options like: --show-minutes (default) --hide-minutes --show-percent --hide-percent (default) to better control what is displayed. Split into more packages ======================== It is quite conceivable that somebody wants to collect battery statistics on one system and analyze it on another. The current package depends on gnuplot - which in turn depends on others and as a result, battery-stats tends to pull in a lot of packages. Which can easily be "too much" (somebody define that, please!) for somebody who just wants the data collected. It should also be possible to analyze the data on a server system without having to pull in libapm - most servers have little use for apm. Packages: battery-stats-collector - the collector battery-stats-grapher - the grapher, depends on gnuplot battery-stats - metapackage, depends on the two above. -- vim:set textwidth=75 autoindent: battery-stats-0.5.6/config.h.cmake000066400000000000000000000002011301330542500170120ustar00rootroot00000000000000#cmakedefine01 HAVE_APM_H #cmakedefine01 HAVE_LIBACPI_H #cmakedefine VERSION_STRING "@VERSION_STRING@" #cmakedefine01 WANT_ACPI battery-stats-0.5.6/data/000077500000000000000000000000001301330542500152355ustar00rootroot00000000000000battery-stats-0.5.6/data/CMakeLists.txt000066400000000000000000000023731301330542500200020ustar00rootroot00000000000000# conf install(FILES conf/battery-stats.conf DESTINATION /etc ) # man if(UNIX) FILE(GLOB MAN1_FILES "man/*.1") FILE(GLOB MAN5_FILES "man/*.5") FILE(GLOB MAN8_FILES "man/*.8") install(FILES ${MAN1_FILES} DESTINATION ${CMAKE_INSTALL_PREFIX}/share/man/man1) install(FILES ${MAN5_FILES} DESTINATION ${CMAKE_INSTALL_PREFIX}/share/man/man5) install(FILES ${MAN8_FILES} DESTINATION ${CMAKE_INSTALL_PREFIX}/share/man/man8) endif() # pixmaps FILE(GLOB PIXMAP_FILES "pixmaps/*.png") install(FILES ${PIXMAP_FILES} DESTINATION ${DATA_DIR}/pixmaps) # Desktop file install( FILES battery-stats.desktop battery-stats-graph.desktop DESTINATION ${CMAKE_INSTALL_PREFIX}/share/applications ) FILE(GLOB PMSLEEP_FILES "pm-utils-sleep.d/*") install( PROGRAMS ${PMSLEEP_FILES} DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/pm-utils/sleep.d ) FILE(GLOB PMPOWER_FILES "pm-utils-power.d/*") install( PROGRAMS ${PMPOWER_FILES} DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/pm-utils/power.d ) FILE(GLOB SYSTEMDSLEEP_FILES "systemd-system-sleep/*") install( PROGRAMS ${SYSTEMDSLEEP_FILES} DESTINATION /lib/systemd/system-sleep ) FILE(GLOB UDEVRULES_FILES "udev-rules.d/*") install( FILES ${UDEVRULES_FILES} DESTINATION /lib/udev/rules.d ) battery-stats-0.5.6/data/battery-stats-graph.desktop000066400000000000000000000004061301330542500225350ustar00rootroot00000000000000[Desktop Entry] Name=Battery Level Graph Type=Application Comment=Battery Level Graph Exec=/usr/share/battery-stats/battery-stats-graph Icon=/usr/share/battery-stats/pixmaps/battery-stats.png Terminal=false Categories=Utility Keywords=battery;graph;viewer;stats battery-stats-0.5.6/data/battery-stats.desktop000066400000000000000000000003621301330542500214370ustar00rootroot00000000000000[Desktop Entry] Name=Battery Charge Graph Type=Application Comment=Battery Charge Graph Exec=/usr/bin/battery-graph Icon=/usr/share/battery-stats/pixmaps/battery-stats.png Terminal=false Categories=Utility Keywords=battery;graph;viewer;stats battery-stats-0.5.6/data/conf/000077500000000000000000000000001301330542500161625ustar00rootroot00000000000000battery-stats-0.5.6/data/conf/battery-stats.conf000066400000000000000000000005471301330542500216450ustar00rootroot00000000000000# Default configuration for battery-stats-collector # # This file is sourced from /etc/init.d/battery-stats ; it should follow normal # /bin/sh syntax. # # Use it to override the parameters to battery-stats-collector(8). If not overridden, the # hard-wired defaults in /etc/init.d/battery-stats apply. ARGS="--interval=60 --flush=10 --ignore-missing-battery" battery-stats-0.5.6/data/man/000077500000000000000000000000001301330542500160105ustar00rootroot00000000000000battery-stats-0.5.6/data/man/battery-graph.1000066400000000000000000000126521301330542500206510ustar00rootroot00000000000000.\" Hey, EMACS: -*- nroff -*- .\" First parameter, NAME, should be all caps .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection .\" other parameters are allowed: see man(7), man(1) .TH BATTERY-GRAPH 1 "September 22, 2002" .\" Please adjust this date whenever revising the manpage. .\" .\" Some roff macros, for reference: .\" .nh disable hyphenation .\" .hy enable hyphenation .\" .ad l left justify .\" .ad b justify to both left and right margins .\" .nf disable filling .\" .fi enable filling .\" .br insert line break .\" .sp insert n+1 empty lines .\" for manpage-specific macros, see man(7) .\" TeX users may be more comfortable with the \fB\fP and .\" \fI\fP escape sequences to invode bold face and italics, .\" respectively. .SH NAME battery-graph \- Show a graph of the battery charge .SH SYNOPSIS .B battery-graph .RI [ options ] .RI [ files ... ] .SH DESCRIPTION Show a graph of the battery charge over time. .PP The files given are assumed to contain battery statistics in the battery-stats(5) format. If no files are specified, the default log files will be used. .PP The options can be used for displaying a different interval. An interval is defined in terms of a \fBfrom\fP timestamp, a \fBto\fP timestamp and a \fBduration\fP. By specifying any two, the third will be calculated automatically. A missing duration will be defaulted to 3 hours. .SH OPTIONS These programs follow the usual GNU command line syntax, with long options starting with two dashes (`-'). .TP .B \-g \fRgeometry\fB, \-\-geometry \fRgeometry Sets the X Windows geometry of the graph. This disables text mode. See X(7) for how to specify the geometry. .TP .B \-D \fRdisplay\fB, \-\-display \fRdisplay Shows the graph on the given display. The same effect can be achieved by setting the DISPLAY environment variable. This disables text mode. See X(7) for valid values. .TP .B \-\-title \fbstring Sets the title of the graph window. By default this will be "Battery Graph". If this is set to the empty string, gnuplot(1) will be allowed set the window title - this can be useful if you want your ~/.Xdefaults to take effect for this. .TP .B \-f \fRdate\fB, \-\-from \fRdate Specifies the start date/time for the graph. This accepts exactly the same date/time specifications as the .B date (1) command - see examples below or the Texinfo manual for date for details. .TP .B \-t \fRdate\fB, \-\-to \fRdate Specifies the ending date/time for the graph. This accepts exactly the same date/time specifications as the .B date (1) command - see examples below or the Texinfo manual for date for details. .TP .B \-s \fRdate\fB, \-\-since \fRdate Shorthand for \-\-from \fIdate\fR \-\-to now .TP .B \-d \fRduration\fB, \-\-duration \fRduration Specifies the duration for the graph. This can be given in units of seconds, hours, days or weeks by suffixing the number with 's' (seconds), 'm' (minutes), \&'h' (hours), 'd' (days) or 'w' (weeks). .br .br Units cannot be combined - e.g. '1d6h' will not be valid, whereas '30h' is OK. If no unit is specified, minutes will be assumed. .TP .B \-\-text Shows the graph in text mode on stdout. The resulting size of the graph is determined by the values of the environment variables. .B LINES and .B COLUMNS (failing that, the output from .B tput will be used). This is the default when the environment variable DISPLAY is not set. .SH EXAMPLES .TP .B Show the last 2 hours: $ battery-graph \-\-duration 2h .TP .B Show the time since mid day: $ battery-graph \-\-from 12:00 \-\-to now .br or .br $ battery-graph \-\-since 12:00 .TP .B Show the hour before last: $ battery-graph \-\-from '2 hours ago' \-\-duration 1h .TP .B Show the 6 hours after noon: $ battery-graph \-\-from 12:00 \-\-duration 6h .br or .br $ battery-graph \-\-from 12:00 \-\-to 18:00 .TP .B Show the last 6 hours $ battery-graph \-\-from '6 hours ago' .br or .br $ battery-graph \-\-since '6 hours ago' .TP .B Show the last 30 minutes in text mode: $ battery-graph \-\-duration 30 \-\-text .TP .B Show statistics for Tuesday last week $ battery-graph \-\-duration 24h \-\-from 'tuesday last week' .br or .br $ battery-graph \-\-duration 1d \-\-from 'tuesday last week' .TP .B Prove that the future hasn't happened yet: $ battery-graph \-\-from yesterday \-\-to tomorrow .TP .B Another way of wasting CPU cycles: $ battery-graph /dev/null .SH EXIT STATUS battery-graph depends on .B gnuplot (1) to give the correct exit status. .SH FILES If no files are given on the command line, batter-graph reads from .I /var/log/battery-stats .SH ENVIRONMENT .TP .B DISPLAY If this variable is not set, \-\-text will be defaulted. .TP .B LINES / COLUMNS Determines the size of the graph in text mode. .SH DIAGNOSTICS If there are no statistics available for the period chosen, an empty graph will result. .SH NOTES There is no requirement for the .I from time to be earlier than the .I to time - if so, the X axis will be reversed. Similar results can be achieved using a negative duration. .PP Also: battery-stat is quite happy to list statistics in the future; stupid, but obedient. .SH AUTHOR This manual page was written by Karl E. Jorgensen , for the Debian GNU/Linux system (but may be used by others). .SH SEE ALSO battery-stats (5), .br date (1), .br battery-stats-collector (8) .br Newer versions of this program may (or may not) be available at .IR http://karl.jorgensen.com/battery-stats .\" vim:set textwidth=75: battery-stats-0.5.6/data/man/battery-log.1000066400000000000000000000031561301330542500203300ustar00rootroot00000000000000.\" Hey, EMACS: -*- nroff -*- .\" First parameter, NAME, should be all caps .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection .\" other parameters are allowed: see man(7), man(1) .TH BATTERY-LOG 1 "November 10, 2002" .\" Please adjust this date whenever revising the manpage. .\" .\" Some roff macros, for reference: .\" .nh disable hyphenation .\" .hy enable hyphenation .\" .ad l left justify .\" .ad b justify to both left and right margins .\" .nf disable filling .\" .fi enable filling .\" .br insert line break .\" .sp insert n+1 empty lines .\" for manpage-specific macros, see man(7) .\" TeX users may be more comfortable with the \fB\fP and .\" \fI\fP escape sequences to invode bold face and italics, .\" respectively. .SH NAME battery-log \- Extract battery statistics .SH SYNOPSIS .B battery-log \fIfiles\fR ... .SH DESCRIPTION Extract battery statistics from the given files to stdout. .PP Files with an extension of .gz will uncompressed automatically. .PP If no files are specified, data will be extracted from .B /var/log/battery-stats* .SH OPTIONS There are no options. .SH EXIT STATUS If any of the files cannot be opened, a non-zero exit code will result. .SH AUTHOR This manual page was written by Karl E. Jorgensen , for the Debian GNU/Linux system (but may be used by others). .SH SEE ALSO battery-stats (5), .br battery-stats-collector (8) .br Newer versions of this program may (or may not) be available at .IR http://karl.jorgensen.com/battery-stats .\" vim:set textwidth=75: battery-stats-0.5.6/data/man/battery-stats-collector.8000066400000000000000000000067471301330542500227110ustar00rootroot00000000000000.\" Hey, EMACS: -*- nroff -*- .\" First parameter, NAME, should be all caps .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection .\" other parameters are allowed: see man(7), man(1) .TH BATTERY-STATS-COLLECTOR 8 "October 30, 2012" .\" Please adjust this date whenever revising the manpage. .\" .\" Some roff macros, for reference: .\" .nh disable hyphenation .\" .hy enable hyphenation .\" .ad l left justify .\" .ad b justify to both left and right margins .\" .nf disable filling .\" .fi enable filling .\" .br insert line break .\" .sp insert n+1 empty lines .\" for manpage-specific macros, see man(7) .\" TeX users may be more comfortable with the \fB\fP and .\" \fI\fP escape sequences to invode bold face and italics, .\" respectively. .SH NAME battery-stats-collector \- Collect statistics about battery charge .SH SYNOPSIS .B battery-stats-collector .RI [ option ] " " ... .SH DESCRIPTION Does exactly as it says on the tin - it will collect information from the APM subsystem and write it to a log file. .PP Normally battery-stats-collector will be invoked by the system startup scripts. .SH OPTIONS battery-stats follow the usual GNU command line syntax, with long options starting with two dashes (`-'). .TP .B \-o \fPFILE\fB, \-\-output \fPFILE Append statistics to the given file. The default filename is .B /var/log/battery-stats .TP .B \-i \fPSECS\fB, \-\-interval=\fPSECS Sampling intervals in seconds. If not specified, stats will be collected every 30 seconds. .TP .B \-F \fPCOUNT\fB, \-\-flush=\fPCOUNT Flushes data to the log file every COUNT samples. A value of zero turns off flushing altogether. If left unspecified, battery-stats-collector will assume a value of 1, i.e. flush at every write. Setting the value too low will tend to keep the disk spinning (and use battery needlessly). Setting the value too high will loose statistics in case of an improper shutdown. .br Note that since battery-stats-collector uses the standard Ansi C library, data will still be flushed periodically (regardless of this setting) once the buffer fills up. The size of the buffer is platform dependent, but 4Kb and 8Kb seem pretty normal. .TP .B \-b \fPNUM\fB, \-\-battery\-num=\fPNUM Read information about battery number NUM. (In case you have multiple batteries installed). .TP .B \-1, \-\-once Only collect a single sample and exit. The default is to loop continiously. .TP .B \-I, \-\-ignore\-missing\-battery Keeps quiet about missing batteries. This stops the warnings on stderr/syslog that would otherwise occur when the battery is missing. .TP .B \-s, \-\-syslog Log error messages to syslog, rather than stderr. Note that messages regarding invalid command line parameters will still go to stderr. .TP .B \-V, \-\-version Show version of battery-stats-collector and exit. .TP .B \-h, \-\-help Show summary of options and exit. .SH FILES .TP .B /var/log/battery-stats Default file for writing battery charge samples to. .SH SEE ALSO .BR battery-graph (1) .br Newer versions of this program may (or may not) be available at .IR http://karl.jorgensen.com/battery-stats .SH AUTHOR This manual page was written initially written by Karl E. Jorgensen , for the Debian GNU/Linux system (but may be used by others). .br Adapted by Antonio Radici to include libacpi and autotools support, see History for details. .br Kevin Funk took over maintainership in 2012. battery-stats-0.5.6/data/man/battery-stats.5000066400000000000000000000047441301330542500207150ustar00rootroot00000000000000.\" Hey, EMACS: -*- nroff -*- .\" First parameter, NAME, should be all caps .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection .\" other parameters are allowed: see man(7), man(1) .TH BATTERY-STATS 5 "September 23, 2002" .\" Please adjust this date whenever revising the manpage. .\" .\" Some roff macros, for reference: .\" .nh disable hyphenation .\" .hy enable hyphenation .\" .ad l left justify .\" .ad b justify to both left and right margins .\" .nf disable filling .\" .fi enable filling .\" .br insert line break .\" .sp insert n+1 empty lines .\" for manpage-specific macros, see man(7) .SH NAME battery-stats \- collected battery statistics .SH DESCRIPTION The battery-stats contains statistics about battery charge over time, as collected by the .B battery-stats-collector (8) daemon. .SH FORMAT Each line in the file represents one sample and is of the form: .ce separated by spaces and terminated by a newline. .PP Where: .TP .B seconds is the number of seconds since 1st Jan 1970 00:00:00 UTC .TP .B charge% is the battery charge a number between 0 and 100 .TP .B powermode indicates the power mode: .RS 16 .B 0 A/C off .br .B 1 On battery .br .B 2 On backup power .RE .TP .B UTC-date a human-readable date in the format YYYY/MM/DD. Note that this is in UTC, not the local or system timezone. .TP .B UTC-time a human-readable time in the format HH:MM:SS (using a 24-hour clock). Note that this is in UTC, not the local or system timezone. .TP .B minutes-left is the BIOS estimate of how many minutes of running time the battery would provide. This may be unreliable, depending on the BIOS through which it was collected. .SH EXAMPLE A battery under charge might result in the following samples: .RS 1032651245 27 1 2002/09/21 23:34:05 94 .br 1032651275 28 1 2002/09/21 23:34:35 97 .br 1032651305 29 1 2002/09/21 23:35:05 100 .br 1032651335 30 1 2002/09/21 23:35:35 103 .br 1032651365 30 1 2002/09/21 23:36:05 106 .RE .SH FILES The default set-up is to save battery statistics in /var/log and rotate the logs weekly, which results in this set of files: .br .I /var/log/battery-stats - current (most recent) statistics .br .I /var/log/battery-stats.[0-9]+ - less recent statistics .br .I /var/log/battery-stats.[0-9]+.gz - ancient statistics .SH SEE ALSO .BR battery-graph (1), .BR battery-stats-collector (8). .SH AUTHOR Karl E. Jorgensen battery-stats-0.5.6/data/pixmaps/000077500000000000000000000000001301330542500167165ustar00rootroot00000000000000battery-stats-0.5.6/data/pixmaps/battery-stats.png000066400000000000000000000055731301330542500222440ustar00rootroot00000000000000PNG  IHDR00WgAMA a pHYsod IDATx[lygfvwʼT&u*%(4/uZiP?X,Z@FѾ%E/6i LdKLJr)-w>s<%%K @?`ٙ9| e~oی= vsei*d<{/*/|1P|(" CAGw܇B`qqW>#SkNaHa:b'Nz!>vV"j/03 <("(} 癝xϹgWhG)\%afP\y_&d}}Žػw#p׿\/RԇG=ϋJ)c"A yEeQ9vؿ%`YgΜannNCV#_( i%"DQGĉbjj%p>||*-,b``|>iד }|ߔ꼔0 ,Gy111X\\C&.JBx$ 0 {'#B{ qFFF8z覜+ ntX\\wޑknj}+r8۶m㥗^ɉ/$1OT^|(CSu)e|$e꒔FR׹K^gvvV1H?KWfxx4Q(W}󘘘رcbxx`uJ\S?c4C aM#DZJ!<!DfĖiMsN"m۴m")i FS`*J~UM[6<,ˊk7GBIK82mnD&BdQE!A:\M i6zz<(MMM:\BixGܔ*19}\uݮ v1&J:c:A( cLOO##fOۊ\Z-זYi8.A2T36:BV(N(D"15}ɷ_~YW'd2=4<Ǐm˅o޳o82::JP葈L۶q7oPJozf6DH"%\[YC1ړLfS=$F Ǐ|'q Z5.^R»鰺J٤hpM:EV<5}Cu\ĆKt'}qgi VXDh^7ogdd!kkkܸqFAV.mznfnKe*2k)#tm  G/|z?HR1lD  ۶ӧj,}a`աlZ|xiCuYV͑l&yYŁ^߉~m׋"򊘚byy9L6܃J}<:gD[GݍؔJ%FFNJ# 69~!ZƩSÇz*lH2R Q.4MC O(J;?P,$efffwߥX,ƽ(! 8CsA>??V즱u iE^}Uq!VWW[F5:y:g-?~`NVdr.TU^udܭ) a7z?< Jp}~"J W\O|甸1ɓ'Efyy3^o0`0ޑ)=,{h/}IENDB`battery-stats-0.5.6/data/pm-utils-power.d/000077500000000000000000000000001301330542500203635ustar00rootroot00000000000000battery-stats-0.5.6/data/pm-utils-power.d/20_battery-stats000077500000000000000000000007651301330542500234300ustar00rootroot00000000000000#!/bin/sh # Action script to collect battery status when the power connector is # inserted or removed. Not working as intended on Debian due to # bug #818649, but worked around by adding udev rule manually. # # Copyright: 2013,2016 Petter Reinholdtsen # License: GPL-2+ # PATH=/sbin:/usr/sbin:/bin:/usr/bin case "${1}" in false|true) if [ -x /usr/share/battery-stats/collect-csv ]; then /usr/share/battery-stats/collect-csv /usr/sbin/battery-stats-collector -1 fi ;; esac battery-stats-0.5.6/data/pm-utils-sleep.d/000077500000000000000000000000001301330542500203375ustar00rootroot00000000000000battery-stats-0.5.6/data/pm-utils-sleep.d/20_battery-stats000077500000000000000000000006421301330542500233760ustar00rootroot00000000000000#!/bin/sh # Action script to collect battery status just before and just after # going to sleep. # # Copyright: Copyright (c) 2013 Petter Reinholdtsen # License: GPL-2+ # PATH=/sbin:/usr/sbin:/bin:/usr/bin case "${1}" in hibernate|suspend|resume|thaw) if [ -x /usr/share/battery-stats/collect-csv ]; then /usr/share/battery-stats/collect-csv /usr/sbin/battery-stats-collector -1 fi ;; esac battery-stats-0.5.6/data/systemd-system-sleep/000077500000000000000000000000001301330542500213555ustar00rootroot00000000000000battery-stats-0.5.6/data/systemd-system-sleep/battery-stats000077500000000000000000000006071301330542500241140ustar00rootroot00000000000000#!/bin/sh # # Collect battery status before and after entering suspend and hibernation # # Copyright: Copyright (c) 2015 Petter Reinholdtsen # License: GPL-2+ case "$1" in pre|post) if [ -x /usr/share/battery-stats/collect-csv ]; then /usr/share/battery-stats/collect-csv /usr/sbin/battery-stats-collector -1 fi ;; suspend|hibernate|hybrid-sleep) # no-op ;; esac battery-stats-0.5.6/data/udev-rules.d/000077500000000000000000000000001301330542500175525ustar00rootroot00000000000000battery-stats-0.5.6/data/udev-rules.d/battery-stats.rules000066400000000000000000000005551301330542500234410ustar00rootroot00000000000000SUBSYSTEM=="power_supply", ACTION=="change", RUN+="/usr/share/battery-stats/collect-csv" SUBSYSTEM=="power_supply", ACTION=="change", RUN+="/usr/sbin/battery-stats-collector -1" SUBSYSTEM=="power_supply", ATTR{online}=="[01]", RUN+="/usr/share/battery-stats/collect-csv" SUBSYSTEM=="power_supply", ATTR{online}=="[01]", RUN+="/usr/sbin/battery-stats-collector -1" battery-stats-0.5.6/src/000077500000000000000000000000001301330542500151135ustar00rootroot00000000000000battery-stats-0.5.6/src/CMakeLists.txt000066400000000000000000000010341301330542500176510ustar00rootroot00000000000000include_directories( ${CMAKE_BINARY_DIR} ) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/battery-graph.in ${CMAKE_CURRENT_BINARY_DIR}/battery-graph @ONLY ) install(PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/battery-graph battery-log DESTINATION bin ) install(PROGRAMS battery-stats-collector DESTINATION sbin ) install(FILES graph-setup DESTINATION ${DATA_DIR} ) install(PROGRAMS collect-csv battery-stats-generate battery-stats-graph battery-stats-graph-flow DESTINATION ${DATA_DIR} ) battery-stats-0.5.6/src/battery-graph.in000066400000000000000000000145061301330542500202220ustar00rootroot00000000000000#!/bin/bash # # This file is part of the battery-stats package. # Copyright (C) 2015 F Zenke # Copyright (C) 2002 Karl E. Jørgensen # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software set -e prefix=@CMAKE_INSTALL_PREFIX@ libdir=${prefix}/@DATA_DIR@ TEMP=`getopt -o f:s:t:d:TAg:D --long from:,since:,to:,duration:,text,norate,title:,geometry:,display:,libdir: -n battery-graph -- "$@"` now=$( date +%s --date=now ) from=0 to=0 duration=0 default_duration=10800 # 3 hours text=false SWITCH_RATE=true title="Battery Graph" eval set -- "$TEMP" while true ; do case "$1" in -f|--from) from=`date --date="$2" +%s` shift 2 ;; -s|--since) from=`date --date="$2" +%s` shift 2 to=`date --date=now +%s` ;; -t|--to) to=`date --date="$2" +%s` shift 2 ;; -d|--duration) case "$2" in *s) duration=$(basename $2 s) ;; *m) duration=$(( $(basename $2 m) * 60 )) ;; *h) duration=$(( $(basename $2 h) * 60 * 60 )) ;; *d) duration=$(( $(basename $2 d) * 24 * 60 * 60 )) ;; *w) duration=$(( $(basename $2 w) * 24 * 60 * 60 * 7 )) ;; *) duration=$(( $2 * 60 )) ;; esac shift 2; ;; -T) echo 1>&2 battery-graph: Warning: Deprecated option "$1": Use --text instead text=true; shift ;; --text) text=true; shift ;; --norate) SWITCH_RATE=false; shift ;; -D|--display) DISPLAY=$2 export DISPLAY shift 2 text=false ;; -g|--geometry) geometry=$2 shift 2 text=false ;; --title) title="$2" shift 2 text=false ;; --libdir) libdir="$2" shift 2 ;; --) shift break; ;; *) echo 1>&2 $0: Internal error - please report as bug '[Parsing args]' exit 2; esac done if [ -z "$DISPLAY" ] ; then text=true fi if [ $from -eq 0 ] && [ $duration -eq 0 ] && [ $to -eq 0 ] then # No options specified at all. duration=$default_duration to=$now fi case "${from}:${duration}:${to}" in 0:0:*) # Only 'to' given from=$(( $to - $default_duration )) ;; 0:*:0) # Only duration given to=$now from=$(( $to - $duration )) ;; 0:*:*) # Only 'duration' and 'to' given from=$(( $to - $duration )) ;; *:0:0) # Only 'from' given to=$(( $from + $default_duration )) ;; *:0:*) # Only 'from' and 'to' given. Great! ;; *:*:0) # Only 'from' and 'duration' given to=$(( $from + $duration )) ;; *:*:*) # All 3 specified. Make sure that they match up if [ $(( $from + $duration )) -ne $to ] ; then echo $0: Inconsistent from/to/duration: $from/$to/$duration exit 2 fi ;; *) echo $0: Internal error - please report bug 1>&2 '[Time calculation]' exit 2 esac # So far, $from and $to are 'seconds since 1st Jan 1970 00:00:00 UTC'. # But gnuplot uses 'seconds since '1st Jan 2000 00:00:00 UTC'... adjustment=$(( $(TZ=UTC date +%s --date='1/1/2000') - $(TZ=UTC date +%s --date='1/1/1970') )) # Adjustment between UTC and local time utc_adjust=$(( $( date -u --date=12:00 +%s) - $(date --date=12:00 +%s) )) adjustment=$(( $adjustment - $utc_adjust )) from2000=$(( $from - $adjustment )) to2000=$(( $to - $adjustment )) TMPFILENAME=`mktemp` # Write battery log to tmp file which allows us to do some more fancy plotting and fitting battery-log "$@" > $TMPFILENAME # Extract time of last charge status change TIME_LAST_RECORD=`tail -n 1 $TMPFILENAME | awk '{ print $1 }'` TIME_LAST_DISCHARGE_BEGIN=`awk "BEGIN {last_status=-1} \ { if (\\\$3!=last_status && \\\$3==1) {tchange = \\\$1} last_status=\\\$3 } \ END {print (tchange)}" $TMPFILENAME` if [ ! "$TIME_LAST_DISCHARGE_BEGIN" ] ; then SWITCH_RATE=false else TIME_LAST_DISCHARGE_END=`awk "BEGIN {last_status=-1} \ { if (\\\$3!=last_status && \\\$3==2) {tchange = \\\$1} last_status=\\\$3 } \ END { if (tchange>$TIME_LAST_DISCHARGE_BEGIN) {print (tchange)} else {print $TIME_LAST_RECORD} }" $TMPFILENAME` fi ZERO_BIOS_ESTIMATE=`tail -n 1 $TMPFILENAME | awk '{ print $6 }'` ( if $text ; then echo set terminal dumb ${COLUMNS:-$(tput cols)} ${LINES:-$(tput lines)} fi echo call \"${libdir}/graph-setup\" # Fitting last discharge segment if SWITCH_RATE is true echo "zero_time=0" # avoid undefined errors if no slope is computed echo "full_time = 1" echo "zero_time_err=0" echo "A = 50.0" echo "B = 1.0" echo "B_err = 0.0" echo "f(x) = A+B*x" echo "g(x) = 0" if $SWITCH_RATE ; then echo "if ($TIME_LAST_DISCHARGE_END>$TIME_LAST_DISCHARGE_BEGIN) { " # makes sure we have a positive interval echo "set fit errorvariables" echo "set fit quiet" echo "fit [0: ($TIME_LAST_DISCHARGE_END-$TIME_LAST_DISCHARGE_BEGIN)] f(x) \"$TMPFILENAME\" using (\$1 - $TIME_LAST_DISCHARGE_BEGIN ):2 via A,B" echo "zero_time = -A/B" echo "zero_time_err = sqrt((A/B**2*B_err)**2+(1.0/B*A_err)**2) }" # in case we want to display estimated time left echo "full_time = (100-A)/B" echo "g(x) = xfull_time?f(x):1/0):1/0" fi echo "set xrange [ $from2000 : $to2000 ] noreverse" echo plot "\"$TMPFILENAME\" using (\$1 - $adjustment):(\$3==2?\$2:1/0) smooth unique axis x1y1 title \"Plugged in\" with lines linecolor rgb \"blue\" linewidth 3, \ \"\" using (\$1 - $adjustment):(\$3==1?\$2:1/0) smooth unique axis x1y1 title \"Discharging\" with lines linecolor rgb \"red\" linewidth 3 \\" if $SWITCH_RATE ; then echo ", g(x -($TIME_LAST_DISCHARGE_BEGIN-$adjustment) ) title (B<0?sprintf(\"slope= (%.2f +/- %.2f) %/h\", B*3600, B_err*3600):\"\") lc rgb \"black\" lt 2 " fi ) | gnuplot -persist ${geometry:+-geometry} $geometry ${title:+-title} "${title}" ; rm -f $TMPFILENAME # TODO Have to decide if we want to clean up or leave the file for us to zoom in/out in the graph # For now we will just go the clean way and delete everything again. rm -f $TMPFILENAME battery-stats-0.5.6/src/battery-log000066400000000000000000000017631301330542500172760ustar00rootroot00000000000000#!/bin/sh # # This file is part of the battery-stats package. # Copyright (C) 2002 Karl E. Jørgensen # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software set -e if [ $# -eq 0 ] then files=`ls -1tr /var/log/battery-stats /var/log/battery-stats.[0-9]* 2>/dev/null` \ || true else files="$@" fi for file in $files do case "$file" in *.gz) zcat $file ;; *) cat $file esac done battery-stats-0.5.6/src/battery-stats-collector000077500000000000000000000101031301330542500216260ustar00rootroot00000000000000#!/bin/sh # # This file is part of the battery-stats package. # Copyright (C) 2016 Petter Reinholdtsen # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software set -e get_logline() { secstamp=$(date +%s) stamp=$(date +"%Y/%m/%d %H:%M:%S") if [ -f /sys/class/power_supply/AC/online ]; then aconline=$(cat /sys/class/power_supply/AC/online) elif [ -f /sys/class/power_supply/ACAD/online ]; then aconline=$(cat /sys/class/power_supply/ACAD/online) elif [ -f /sys/class/power_supply/ADP1/online ]; then aconline=$(cat /sys/class/power_supply/ADP1/online) else echo "No power supply found" fi if [ 1 = "$aconline" ]; then state=2 else state=1 fi now="energy_now" full="energy_full" for f in /sys/class/power_supply/BAT*; do [ -e "$f" ] || continue if [ ! -e $f/$now ] ; then now="charge_now"; fi if [ ! -e $f/$full ] ; then full="charge_full"; fi energy_now=$(cat $f/$now) # uWh energy_full=$(cat $f/$full) # uWh percent=$( (echo scale=2; echo "100 * $energy_now / $energy_full") | bc -l) # FIXME figure out how to calculate minutes remaining the same # way libacpi calculate it. # Ideas: if false; then power_now=$(cat $f/power_now) # uW voltage_now=$(cat $f/voltage_now) # uV rate=$(( 1000000 * $power_now / $voltage_now)) if [ 0 = $rate ] ; then minremaining=0 else minremaining=$(( 60 * $energy_now / $rate )) fi # 10^6 * uW / uV = uA remaining_capasity=$((1000000 * $energy_now / $voltage_now )) # 10^6 * uA / uW = 1 / mV minremaining=$((1000000 * $remaining_capasity / $power_now)) fi break done # Use '-' for minutes remaining, as this value isn't used by the # graph drawing system. echo $secstamp $percent $state $stamp - } usage() { cat <> $logfile else get_logline fi if [ 0 -lt $sample_interval_secs ] ; then sleep $sample_interval_secs else break fi done battery-stats-0.5.6/src/battery-stats-generate000077500000000000000000000046571301330542500214530ustar00rootroot00000000000000#!/usr/bin/python import argparse import itertools import random import re import time def header(): fields = re.split(r'\s+', """timestamp manufacturer model_name technology serial_number energy_full energy_full_design energy_now cycle_count status""") print(','.join(fields)) def change_charge(odds = 0.5, factor = 10, mult = -1): if int(random.random() < odds): return factor else: return mult * factor def generate(args): now = int(time.time()) energy_now = energy_full = energy_full_design = random.randint(1000000, 1000000*10) status = 'Charging' for i in itertools.count(args.limit, -1): energy_now = max(0, min(energy_now, energy_full)) fields = [ now ] fields += map(lambda x: '', range(4)) fields += [ energy_full, energy_full_design, energy_now, '', status ] fields = map(str, fields) print(','.join(fields)) # remove or add between 0 and 10% of the charge, half the time energy_now += change_charge(args.discharge_prob, factor=random.randint(0, energy_full/args.discharge_rate)) # around one out of 3 changes to remove around 0.1% of charge energy_full -= change_charge(args.damage_prob, mult = 0, factor=random.randint(0, energy_full/args.damage_rate)) now += args.wait if not i: break parser = argparse.ArgumentParser() parser.add_argument('--limit', '-n', type=int, default=-1, help='how many entries to generate (default: %(default)s or infinity)') parser.add_argument('--wait', '-w', type=int, default=10*60, help='the wait time between the simulated samples, in seconds (default: %(default)s)') parser.add_argument('--discharge_rate', '-d', type=int, default=10, help='discharge rate, in percentage (default: %(default)s)') parser.add_argument('--discharge_prob', type=float, default=0.5, help='discharge probability (default: %(default)s)') parser.add_argument('--damage_rate', '-a', type=int, default=10000, help='discharge rate, in percentage (default: %(default)s)') parser.add_argument('--damage_prob', type=float, default=0.33, help='discharge probability (default: %(default)s)') args = parser.parse_args() header() generate(args) battery-stats-0.5.6/src/battery-stats-graph000077500000000000000000000163061301330542500207540ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- # # This file is part of the battery-stats package. # Copyright (C) 2015 Antoine Beaupré # 2016 Petter Reinholdtsen # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software import argparse import datetime import fileinput import glob import logging import os import sys import time from matplotlib.ticker import FuncFormatter import matplotlib import matplotlib.pyplot as plt import numpy as np parser = argparse.ArgumentParser() parser.add_argument('logfile', nargs='*', default='/var/log/battery-stats.csv*', help='logfile to read (default: %(default)s)') parser.add_argument('--output', type=argparse.FileType('w'), default=sys.stdout, help='image to write (default to terminal if available, otherwise stdout)') parser.add_argument('--death', type=int, default=5, help='percentage of battery when it is considered dead (default: %(default)s)') args = parser.parse_args() if type(args.logfile) is str: args.logfile = glob.glob(args.logfile) logfiles = fileinput.input(args.logfile, openhook=fileinput.hook_compressed) now = 'energy_now' full = 'energy_full' full_design = 'energy_full_design' def parse_csv_np(): logging.debug('loading CSV file %s with NumPy', args.logfile) data = np.genfromtxt(logfiles, delimiter=',', names=True, filling_values = 0.0) # convert timestamp to datetime, but also select only relevant # fields to avoid having to specify all # XXX: it seems that datetime is not what plot expects, so stick # with float and we convert later #return data.astype([('timestamp', 'datetime64[s]'), # ('energy_full', 'f'), # ('energy_full_design', 'f'), # ('energy_now', 'f')]) return data def parse_csv_builtin(fields = ['timestamp', 'energy_full', 'energy_full_design', 'energy_now', 'charge_now', 'charge_full', 'charge_full_design' ]): import csv logging.debug('loading CSV file %s with builtin CSV module', args.logfile) log = csv.DictReader(logfiles) data = [] try: for row in log: v = [] for f in fields: if f not in row or '' == row[f]: v.append(None) else: v.append(row[f]) l = tuple(v) data.append(l) except csv.Error as e: logging.warning('CSV file is corrupt, skipping remaining entries: %s', e) logging.debug('building data array') return np.array(data, dtype=zip(fields, 'f'*len(fields))) # the builtin CSV parser above is faster, we went from 8 to 2 seconds # on our test data here there are probably other ways of making this # even faster, see: # # http://stackoverflow.com/a/25508739/1174784 # http://softwarerecs.stackexchange.com/a/7510/506 # # TL;DR: performance is currently fine, it could be improved with # Numpy.fromfile(), Numpy.load() or pandas.read_csv() which should # apparently all outperform the above code by an order of magnitude parse_csv = parse_csv_builtin def to_percent(y, position): # Ignore the passed in position. This has the effect of scaling # the default tick locations. s = str(100 * y) # The percent symbol needs escaping in latex if matplotlib.rcParams['text.usetex']: return s + r'$\%$' else: return s + '%' def build_graph(data): logging.debug('building graph') # create vectorized converter (can take list-like objects as # arguments) dateconv = np.vectorize(datetime.datetime.fromtimestamp) dates = dateconv(data['timestamp']) fig, ax = plt.subplots() # XXX: can't seem to plot all at once... #plt.plot(dates, data[now], '-b', data[full], '-r') # ... but once at a time seems to do the result i am looking for ax.plot(dates, data[full_design] / data[full_design], linestyle = '-', color = 'black', label='design') ax.plot(dates, data[now] / data[full_design], linestyle = '-', linewidth = 0.1, color='grey', label='current') ax.plot(dates, data[full] / data[full_design], linestyle = '-', color = 'red', label='effective') # legend and labels ax.legend(loc='upper right') ax.set_xlabel('time') ax.set_ylabel('percent') ax.set_title('Battery capacity statistics') # Tell matplotlib to interpret the x-axis values as dates ax.xaxis_date() # Make space for and rotate the x-axis tick labels fig.autofmt_xdate() # Create the formatter using the function to_percent. This # multiplies all the dfault labels by 100, making them all # percentages formatter = FuncFormatter(to_percent) # Set the formatter ax.yaxis.set_major_formatter(formatter) def render_graph(): if args.output == sys.stdout and \ ('DISPLAY' in os.environ or sys.stdout.isatty()): logging.info("drawing on tty") plt.show() else: logging.info('drawing to file %s', args.output) plt.savefig(args.output, bbox_inches='tight') def guess_expiry(x, y, zero = 0): fit = np.polyfit(data[full], data['timestamp'], 1) #print "fit: %s" % fit fit_fn = np.poly1d(fit) #print "fit_fn: %s" % fit_fn return datetime.datetime.fromtimestamp(fit_fn(zero)) if __name__ == "__main__": logging.basicConfig(format='%(message)s', level=logging.DEBUG) data = parse_csv() if str(data[full_design][1]) in ['', 'nan']: logging.warning('switching to charge_* prefix') now = 'charge_now' full = 'charge_full' full_design = 'charge_full_design' # XXX: this doesn't work because it counts all charge/discharge # cycles, we'd need to reprocess the CSV to keep only the last # continuous states #death = guess_expiry(data[now], data['timestamp']) #logging.info("this battery will be depleted in %s, on %s", # death - datetime.datetime.now(), death) # actual energy at which the battery is considered dead # we compute the mean design capacity, then take the given percentage out of that logging.debug('guessing expiry') zero = args.death * np.mean(data[full_design]) / 100 death = guess_expiry(data[full], data['timestamp'], zero) logging.info("this battery will reach end of life (%s%%) in %s, on %s", args.death, death - datetime.datetime.now(), death) build_graph(data) render_graph() battery-stats-0.5.6/src/battery-stats-graph-flow000077500000000000000000000043151301330542500217160ustar00rootroot00000000000000#!/bin/sh # # This file is part of the battery-stats package. # Copyright (C) 2016 Petter Reinholdtsen # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software input=/var/log/battery-stats.csv filename="${1}" flowfilename=$(mktemp) perl -MText::CSV <<'EOF' > "$flowfilename" use strict; use warnings; my $csv = Text::CSV->new(); my $fh; open $fh, "<:encoding(utf8)", '/var/log/battery-stats.csv' or die "open failed: $!"; my $last2 = undef; my $lasttime2 = undef; my $last = undef; my $lasttime = undef; my @fieldsrow = $csv->getline($fh); my $levelrow = 8; # energy_now while (my $row = $csv->getline($fh) ) { if (defined $last2) { my $diff = $row->[$levelrow] - $last2; my $timediff = $row->[0] - $lasttime2; if (0 < $timediff) { printf "%s,%.2f\n", $row->[0], $diff / $timediff; } } $last2 = $last; $lasttime2 = $lasttime; $last = $row->[$levelrow]; $lasttime = $row->[0]; } $csv->eof or $csv->error_diag(); close($fh); EOF # manufacturer,model_name,technology type=$(head -2 "$input" | tail -1 | cut -d, -f2-4 | tr , " ") ( echo set xdata time echo set timefmt \"%s\" echo set format x \"%Y\" echo set datafile separator \",\" echo set title \'Battery statistics $type\' echo set ylabel \'Flow per second\' echo set xlabel \'Year\' echo set grid if [ "$filename" ]; then echo set term png echo set output \"$filename\" fi echo plot "\"$flowfilename\" using 1:2 smooth unique axis x1y1 title \"Energy flow\" with lines" ) | gnuplot -p if [ "$filename" ] ; then echo "PNG graph $filename created." fi rm $flowfilename battery-stats-0.5.6/src/battery-stats-graph-gnuplot000077500000000000000000000020161301330542500224330ustar00rootroot00000000000000#!/bin/sh # License: GNU Public License v2 or later at your choice. input=/var/log/battery-status.csv filename="${1}" # manufacturer,model_name,technology type=$(head -2 "$input" | tail -1 | cut -d, -f2-4 | tr , " ") ( cat < # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # # Inspired by # http://www.ifweassume.com/2013/08/the-de-evolution-of-my-laptop-battery.html # See also # http://blog.sleeplessbeastie.eu/2013/01/02/debian-how-to-monitor-battery-capacity/ logfile=/var/log/battery-stats.csv files="manufacturer \ model_name \ technology \ serial_number \ status \ cycle_count \ energy_now \ energy_full \ energy_full_design \ charge_now \ charge_full \ charge_full_design \ " TEMP=$(getopt --name collect-csv --options o: --longoptions output: -- "$@") eval set -- "$TEMP" while true; do case "$1" in -o|--output) logfile="$2"; shift 2; continue ;; --) # no more arguments to parse break ;; *) printf "Unknown option %s\n" "$1" exit 1 ;; esac done if [ ! -e "$logfile" ] ; then ( printf "timestamp,when," for f in $files; do printf "%s," $f done echo ) > "$logfile" fi log_battery() { printf "%s,%s," "$(date +%s)" "$(date --iso-8601=seconds)" for f in $files; do for file in $(echo $f | tr / " "); do if [ -e $file ] ; then fexist=$file; else fexist= ; fi done if [ "$fexist" ] && [ -e "$fexist" ] ; then printf "%s," "$(cat $fexist | sed -s 's/\(.* .*\)/"\1"/' )" else printf "," fi done } cd /sys/class/power_supply for bat in $(find -L . -maxdepth 1 -name "BAT*" -type d); do # Print complete message in one echo call, to avoid race condition # when several log processes run in parallel. (cd $bat && echo $(log_battery)) >> "$logfile" done battery-stats-0.5.6/src/graph-setup000066400000000000000000000047761301330542500173130ustar00rootroot00000000000000# This file is part of the battery-stats package. # Copyright (C) 2002 Karl E. Jørgensen # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # set noclip points set clip one set noclip two set bar 1.000000 set border 31 lt -1 lw 1.000 set xdata time set format x "%H:%M\n%d %b" #set xlabel "Date/Time" set xzeroaxis lt -2 lw 1.000 set xtics border mirror norotate autofreq set mxtics default set grid xtics nomxtics set ydata set format y "% g" set ylabel "%Full" set ylabel offset 0,0 set yrange [ 0 : 100 ] set yzeroaxis lt -2 lw 1.000 set ytics border mirror norotate autofreq # 0, 10 set mytics 2 set grid ytics nomytics #set y2data #set format y2 "% g" #set y2zeroaxis lt -2 lw 1.000 #set my2tics default #set noy2tics #set y2tics border nomirror norotate autofreq #set y2label "minutes" 0.000000,0.000000 "" #set y2range [ 0 : * ] noreverse nowriteback # (currently [-10.0000:10.0000] ) #set grid noy2tics nomy2tics set dummy x,y set key title "" set key noreverse box linetype -2 linewidth 1.000 samplen 4 spacing 1 width 0 set key bmargin set key horizontal #set nokey set nolabel set noarrow set nologscale set offsets 0, 0, 0, 0 set pointsize 1 set encoding default set nopolar set noparametric set view 60, 30, 1, 1 set samples 100, 100 set isosamples 10, 10 set surface set nocontour set clabel '%8.3g' set mapping cartesian set nohidden3d set cntrparam order 4 set cntrparam linear set cntrparam levels auto 5 set cntrparam points 5 set size ratio 0 1,1 set origin 0,0 #set data style points #set function style lines set tics in set ticslevel 0.5 set tics scale 1 #set title "" 0.000000,0.000000 "" #set timestamp "" bottom norotate 0.000000,0.000000 "" #set timefmt "%Y/%m/%d %H:%M:%S" #set yrange [ * : * ] noreverse nowriteback # (currently [-10.0000:10.0000] ) set zero 1e-08 set lmargin -1 set bmargin -1 set rmargin -1 set tmargin -1 #set locale "C"