MacBookのバッテリー残量表示

30分プログラム、その561。MacBookのバッテリー残量表示をしてみる。
Linuxなら/proc/acpi/battery/BAT1にバッテリーの情報が書いてあるけど、Macの場合はsystem_profilerで取得できるらしい。-xmlをつければXMLで出力できるけど、驚くほど構造化されていなかったのでプレインテキストでがんばった。

使い方

$ gosh battery.scm
50.21815915229586

ソースコード

#! /opt/local/bin/gosh
;; -*- mode:scheme; coding:utf-8 -*-
;;
;; battery.scm -
;;
;; Copyright(C) 2009 by mzp
;; Author: MIZUNO Hiroki / mzpppp at gmail dot com
;; http://howdyworld.org
;;
;; Timestamp: 2009/04/08 21:16:33
;;
;; This program is free software; you can redistribute it and/or
;; modify it under MIT Lincence.
;;

(use gauche.process)
(use gauche.regexp)

(define (system-profiler)
  (let1 process (run-process "system_profiler" "SPPowerDataType" :output :pipe)
    (process-wait process)
    (port->string (process-output process))))

(define (charge-remain s)
  (rxmatch-let (rxmatch #/Charge remaining \(mAh\):\s+(\d*)/ s)
      (#f remain)
    (string->number remain)))

(define (full-capacity s)
  (rxmatch-let (rxmatch #/Full charge capacity \(mAh\):\s+(\d*)/ s)
      (#f full)
    (string->number full)))

(define (main args)
  (let1 s (system-profiler)
    (print (* 100 (/. (charge-remain s)
		      (full-capacity s))))))