import time
from ptsexcept import *


class ds18d20():

	# ROM commands
	ROM_SEARCH =0xF0
	ROM_READ =0x33
	ROM_MATCH =0x55
	ROM_SKIP =0xCC
	ROM_ALARM_SEARCH =0xEC

	# DS18B20 functions commands
	CONVERT_TEMP =0x44
	WRITE_SCRATCHPAD =0x4E
	READ_SCRATCHPAD =0xBE
	COPY_SCRATCHPAD =0x48
	RECALL_EEPROM =0xB8
	READ_POWER_SUPPLY =0xB4

	def __init__(self, onewire):
		self.iface = onewire
		self.serial = []


	def read_serial(self):
		det = self.iface.reset()

		if not det:
			raise PtsError("1Wire device not detected!")
		else:
			print "Detected a 1Wire device"

		self.iface.write_byte(self.ROM_READ)

		self.serial = self.iface.read_block(8)

		self.serial_int = 0
		for i in xrange(8):
			self.serial_int|=self.serial[i] << (8*i)

		print "Serial: 0x%x" % self.serial_int

	def access(self):

		if self.serial ==[]:
			self.read_serial()

		if not self.iface.reset():
			raise PtsError("1Wire device not detected!")

		self.iface.write_byte(self.ROM_MATCH)
		self.iface.write_block(self.serial)


	def read_temperature(self):

		self.access()
		self.iface.write_byte(self.CONVERT_TEMP)
		time.sleep(1)

		self.access()
		self.iface.write_byte(self.READ_SCRATCHPAD)
		buff = self.iface.read_block(9)

		temp = buff[1]<<8 | buff[0]

		if(temp & 0xF800):
		    temp -= 0x10000
		
		temp /= 16.0
		print "Temperature: %f" % temp

		return temp