import sys
import time

import smbus

class TMP512(object):

    def __init__(self, address):
        self.bus = smbus.SMBus(1)
        self.address = address

        # Shunt Measurement Configuration 
        #   - turn off shunt/bus voltage measurement
        self.write_reg(0x00, 0x3998)

        # Temperature Measurement Configuration
        #   - continous conversion at 1 conversion/second
        #   - enable remote 1, remote 2 and local
        self.write_reg(0x01, 0xBE00)

    def _reverse16(self, value):
        """ A quick hack method for reversing byte order for a 16 bit value """
        str_val = '%04X' % value
        new_val = str_val[2:4] + str_val[0:2]
        return int(new_val, 16)

    def read_reg(self, reg):
        raw = self.bus.read_word_data(self.address, reg)
        return self._reverse16(raw)

    def write_reg(self, reg, data):
        raw = self._reverse16(data)
        self.bus.write_word_data(self.address, reg, raw)

    def reset(self):
        self.write_reg(0x00, 0xB998)
        time.sleep(1)

    def status(self):
        return self.read_reg(0x02)

    def device_id(self):
        return '0x%04X' % self.read_reg(0x1F)

    def _convert_temp(self, raw_val):
        # Raw temp is a 13 bit number, the units are 0.0625 C
        temp = (raw_val >> 3) * 0.0625
        # Convert C to F
        return (temp * 1.8) + 32

    def local_temp(self):
        return self._convert_temp(self.read_reg(0x08))

    def temp_sensor1(self):
        return self._convert_temp(self.read_reg(0x09))

    def temp_sensor2(self):
        return self._convert_temp(self.read_reg(0x0A))


def main():
    import time

    tmp512_1 = TMP512(0x5d)
    tmp512_2 = TMP512(0x5c)

    print 'TMP512-1 status: 0x%04X' % tmp512_1.status()
    print 'TMP512-2 status: 0x%04X' % tmp512_2.status()

    print 'TMP512-1 local temp is %d' % tmp512_1.local_temp()
    print 'TMP512-2 local temp is %d' % tmp512_2.local_temp()

    print 'TMP512-1 remote 1 temp is %d' % tmp512_1.temp_sensor1()
    print 'TMP512-1 remote 2 temp is %d' % tmp512_1.temp_sensor2()
    print 'TMP512-2 remote 1 temp is %d' % tmp512_2.temp_sensor1()
    print 'TMP512-2 remote 2 temp is %d' % tmp512_2.temp_sensor2()

    print '---'
    time.sleep(1)

    print 'TMP512-1 remote 1 temp is %d' % tmp512_1.temp_sensor1()
    print 'TMP512-1 remote 2 temp is %d' % tmp512_1.temp_sensor2()
    print 'TMP512-2 remote 1 temp is %d' % tmp512_2.temp_sensor1()
    print 'TMP512-2 remote 2 temp is %d' % tmp512_2.temp_sensor2()

    print '---'
    time.sleep(1)

    print 'TMP512-1 remote 1 temp is %d' % tmp512_1.temp_sensor1()
    print 'TMP512-1 remote 2 temp is %d' % tmp512_1.temp_sensor2()
    print 'TMP512-2 remote 1 temp is %d' % tmp512_2.temp_sensor1()
    print 'TMP512-2 remote 2 temp is %d' % tmp512_2.temp_sensor2()


if __name__ == '__main__':
    sys.exit(main())