2011年11月29日火曜日

USB温度・湿度計モジュール(USBRH)をPythonで使う

ストロベリー・リナックスの USB温度・湿度計モジュール(USBRH)の USBMeter.dllをPythonから使えるようにしてみた。
# -*- coding: utf-8 -*-
# usbrh.py 2011.11.29
import ctypes

class usbrh:
    def __init__(self):
        # USBMeter.dllの読み込み
        self.dll = ctypes.windll.LoadLibrary('USBMeter')
        self.dev = self.FindUSB()

    def GetVers(self): # ファームウェアバージョンの取得
        f = getattr(self.dll, "_GetVers@4")
        f.restype = ctypes.c_char_p
        f.argtypes = [ctypes.c_char_p]
        return f(self.dev)

    def FindUSB(self, index = 0): # モジュールの検索
        self.index = ctypes.c_int(index)
        f = getattr(self.dll, "_FindUSB@4")
        f.restype = ctypes.c_char_p
        f.argtypes = [ctypes.c_void_p]
        return f(ctypes.byref(self.index))

    def GetTempHumidTrue(self): # 温度・湿度の取得
        temp = ctypes.c_double()
        humid = ctypes.c_double()
        f = getattr(self.dll, "_GetTempHumidTrue@12")
        f.argtypes = [ctypes.c_char_p, ctypes.c_void_p, ctypes.c_void_p]
        r = f(self.dev, ctypes.byref(temp), ctypes.byref(humid))
        if r == 0:
            return [temp.value, humid.value]
        return None

    def ControlIO(self, port, val): # LEDの制御
        f = getattr(self.dll, "_ControlIO@12")
        f.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_int]
        return f(self.dev, port, val)

if __name__ == '__main__':
    import time
    rh = usbrh()
    print "FindUSB [%s]" % rh.dev
    print "GetVers [%s]" % rh.GetVers()
    n = 0
    while 1:
        print rh.GetTempHumidTrue()
        rh.ControlIO(n & 1, n & 2)
        n += 1
        time.sleep(10)


0 件のコメント: