import sys
import time

import smbus

class TMP512(object):

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

    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 device_id(self):
        return '0x%04X' % self.read_reg(0x1F)

    def _convert_temp(self, raw_val):
        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():

    temp1 = TMP512(0x5c)
    temp2 = TMP512(0x5d)
    print '0x%04X' % temp1.read_reg(0x01)
    print '0x%04X' % temp1.read_reg(0x09)
    print '0x%04X' % temp1.read_reg(0x00)
    print temp1.device_id()
    print 'The local temp1 is %d' % temp1.local_temp()
    print 'The local temp2 is %d' % temp2.local_temp()
    print 'The remote1 temp1 is %d' % temp1.temp_sensor1()
    print 'The remote2 temp1 is %d' % temp1.temp_sensor2()

    # bus = smbus.SMBus(1)
    # address = 0x5c
    # # 2 digits at 9ma sink
    # # bus.write_byte_data(self.address, 0x00, 0x35)
    # print '0x%02X' % bus.read_word_data(address, 0x00)
    # print '0x%02X' % bus.read_word_data(address, 0x1F)
    


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