#!/usr/bin/python
import struct, array, time, io, fcntl, sys

I2C_SLAVE=0x0703

# select address according to jumper setting
# address  (40,41,42,43) can be found with
# sudo i2cdetect -y 1
#
# Kommandozeilen-Argument: Sensor-Adresse (LSB)
# 0, 1, 2 oder 3 --> 0x40, 0x41, 0x42 oder 0x43
# Default: 3 --> 0x43

if len(sys.argv) == 2:
  HDC1008_ADDR = (int(sys.argv[1]) % 4) + 0x40
else:
  HDC1008_ADDR = 0x43
print("Adresse:  %7x" % HDC1008_ADDR)

bus = 1
fr = io.open("/dev/i2c-"+str(bus), "rb", buffering=0)
fw = io.open("/dev/i2c-"+str(bus), "wb", buffering=0)

# set device address
fcntl.ioctl(fr, I2C_SLAVE, HDC1008_ADDR)
fcntl.ioctl(fw, I2C_SLAVE, HDC1008_ADDR)
time.sleep(0.015) # 15ms startup time

# set config register
s = [0x02,0x02,0x00]
s2 = bytearray(s)
fw.write(s2) #sending config register bytes
time.sleep(0.015) # From the data sheet

# read temperature
s = [0x00]
s2 = bytearray(s)
fw.write(s2)
time.sleep(0.0625) # From the data sheet
data = fr.read(2)  # read 2 byte temperature data
buf = array.array('B', data)
temp = ((((buf[0]<<8) + (buf[1]))/65536.0)*165.0) - 40.0
print ("Temperatur:  %7.2f" % temp)
time.sleep(0.015)  # From the data sheet

# read humidity
s = [0x01]
s2 = bytearray(s)
fw.write(s2)
time.sleep(0.0625) # From the data sheet
data = fr.read(2)  # read 2 byte temperature data
buf = array.array('B', data)
humid = ((((buf[0]<<8) + (buf[1]))/65536.0)*100.0)
print ("Luftfeuchte: %7.2f%%" % humid)
