#! /usr/bin/python
__author__ = "J Dean Brock"

from smbus import SMBus
import time
import json

RPI_I2C_BUS = 1

# I2C device addresses
BMP180ADDR = 0x77

BMP180_CHIPID_REG =         0xD0
BMP180_CHIPID_VALUE =       0x55

# Various constants
# obtained from bmp180.h
# in https://github.com/mozilla-b2g/kernel-android-galaxy-s2-ics

# Register addresses
BMP180_TAKE_MEAS_REG =      0xF4
BMP180_READ_MEAS_REG =      0xF6
BMP180_EEPROM_AC1 =         0xAA
BMP180_EEPROM_AC2 =         0xAC
BMP180_EEPROM_AC3 =         0xAE
BMP180_EEPROM_AC4 =         0xB0
BMP180_EEPROM_AC5 =         0xB2
BMP180_EEPROM_AC6 =         0xB4
BMP180_EEPROM_B1 =          0xB6
BMP180_EEPROM_B2 =          0xB8
BMP180_EEPROM_MB =          0xBA
BMP180_EEPROM_MC =          0xBC
BMP180_EEPROM_MD =          0xBE

# constants for what we want to measure  (I have no idea...)
BMP180_MEAS_TEMP =              0x2E
BMP180_MEAS_PRESS_OVERSAMP_0 =  0x34
BMP180_MEAS_PRESS_OVERSAMP_1 =  0x74
BMP180_MEAS_PRESS_OVERSAMP_2 =  0xB4
BMP180_MEAS_PRESS_OVERSAMP_3 =  0xF4

# BMP180 in big-endian order
def readBEWord(bus, dev, addr):
    bew = bus.read_word_data(dev, addr) 
    bms = bew & 0xFF
    if bms >= 128:
        bms = bms - 256
    bls = (bew >> 8) & 0xFF
    return bms*256 + bls

def readBMP180temp():
    bmp180bus = SMBus(RPI_I2C_BUS)

    # Read the EEPROM configuration values
    ac5 = readBEWord(bmp180bus, BMP180ADDR, BMP180_EEPROM_AC5)
    ac6 = readBEWord(bmp180bus, BMP180ADDR, BMP180_EEPROM_AC6)
    mc  = readBEWord(bmp180bus, BMP180ADDR, BMP180_EEPROM_MC)
    md  = readBEWord(bmp180bus, BMP180ADDR, BMP180_EEPROM_MD)

    # Start the read
    bmp180bus.write_byte_data(BMP180ADDR,
                              BMP180_TAKE_MEAS_REG, BMP180_MEAS_TEMP)
    # Supposed to wait 4.5ms
    time.sleep(0.01)
    ut  = readBEWord(bmp180bus, BMP180ADDR, BMP180_READ_MEAS_REG)
    x1 = (ut-ac6)*ac5/32768
    x2 = mc * 2048 / (x1 + md)
    b5 = x1 + x2
    ut = (b5 + 8) / 16
    c = ut * 0.1
    return c

def main():
    c = readBMP180temp()
    jsonret = json.dumps({'temperature': c})
    print jsonret
    return

if __name__ == "__main__":
    main()


