2011年11月20日日曜日

PC (Linux)のバッテリ残量を調べる

PC(Linux)のバッテリ容量をプログラムから知りたいことがあったのでPythonで作ってみました。
例によって参考程度になればと貼っておきます。
他にもっといい方法あれば教えてください。

一応ノードも作りました。

  1. #! /usr/bin/env python  
  2.   
  3. import re  
  4.   
  5. class AcpiChecker():  
  6.     """read /proc/acpi/battery/*** files for check the PC's battery"""  
  7.     def __init__(self, battery_name):  
  8.         self._info_path = "/proc/acpi/battery/" + battery_name + "/info"  
  9.         self._state_path = "/proc/acpi/battery/" + battery_name + "/state"  
  10.     def get_capacity(self):  
  11.         f = open(self._info_path)  
  12.         for line in f:  
  13.             match = re.search(r'^last full capacity:\s*(\d+)', line)  
  14.             if match:  
  15.                 capacity = match.groups()[0]  
  16.         f.close()  
  17.         return capacity  
  18.   
  19.     def get_state(self):  
  20.         f = open(self._state_path)  
  21.         for line in f:  
  22.             match = re.search(r'^remaining capacity:\s*(\d+)', line)  
  23.             if match:  
  24.                 state = match.groups()[0]  
  25.         f.close()  
  26.         return state  
  27.   
  28.     def get_rate(self):  
  29.         return float(self.get_state()) / float(self.get_capacity())  
  30.   
  31. if __name__=='__main__':  
  32.     checker = AcpiChecker('BAT0')  
  33.     print checker.get_rate()  

ノードはこんな感じでてきとーに作ってみました。


  1. #! /usr/bin/env python  
  2.   
  3. import roslib  
  4. roslib.load_manifest('otl_battery_checker')  
  5.   
  6. import rospy  
  7. from std_msgs.msg import Float64  
  8. from battery_check import AcpiChecker  
  9.   
  10. class BatteryCheckerNode():  
  11.     """check battery and publish the charge rate"""  
  12.     def __init__(self, battery_name='BAT0'):  
  13.         self._checker = AcpiChecker(battery_name)  
  14.         self._pub = rospy.Publisher('/pc/battery_rate', Float64)  
  15.     def proc(self):  
  16.         msg = Float64()  
  17.         msg.data = self._checker.get_rate()  
  18.         self._pub.publish(msg)  
  19.   
  20. if __name__=='__main__':  
  21.     rospy.init_node('pc_battery_checker')  
  22.     battery_name = 'BAT0'  
  23.     if rospy.has_param('~device'):  
  24.         battery_name = rospy.get_param('~device')  
  25.     check = BatteryCheckerNode(battery_name)  
  26.     rate = rospy.Rate(1)  
  27.     while not rospy.is_shutdown():  
  28.         check.proc()  
  29.         rate.sleep()  


参考にしたサイト

0 件のコメント:

コメントを投稿