Yet Another WebIOPi+
 All Classes Namespaces Files Functions Variables Macros Pages
hytXXX.py
Go to the documentation of this file.
1 # Copyright 2014 Michael Burget, Eric PTAK
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 
15 from time import sleep
16 from webiopi.utils.types import toint
17 from webiopi.devices.i2c import I2C
18 from webiopi.devices.sensor import Temperature,Humidity
19 
21  VAL_RETRIES = 30
22 
23  def __init__(self, slave=0x28):
24  I2C.__init__(self, toint(slave))
25  self.__startMeasuring__()
26 
27  def __str__(self):
28  return "HYT221(slave=0x%02X)" % self.slave
29 
30  def __family__(self):
31  return [Temperature.__family__(self), Humidity.__family__(self)]
32 
33  def __startMeasuring__(self):
34  self.writeByte(0x0)
35 
36  def readRawData(self):
37  self.__startMeasuring__()
38  for i in range(self.VAL_RETRIES):
39  #C-code example from sensor manufacturer suggest to wait 100ms (Duration of the measurement)
40  # no to get the very last measurement shoudn't be a problem -> wait 10ms
41  # try a read every 10 ms for maximum VAL_RETRIES times
42  sleep(.01)
43  data_bytes=self.readBytes(4)
44  stale_bit = (data_bytes[0] & 0b01000000) >> 6
45  if (stale_bit == 0):
46  raw_t = ((data_bytes[2] << 8) | data_bytes[3]) >> 2
47  raw_h = ((data_bytes[0] & 0b00111111) << 8) | data_bytes[1]
48  return (raw_t, raw_h)
49 
50  #Stale was never 0, so datas are not actual
51  raise Exception("HYT221(slave=0x%02X): data fetch timeout" % self.slave)
52 
53 
54  def __getCelsius__(self):
55  (raw_t, raw_h) = self.readRawData()
56  if raw_t < 0x3FFF:
57  return (raw_t * 165.0 / 2**14) - 40.0
58  else:
59  raise ValueError("Temperature value out of range (RawValue=0x%04X Max:0x3FFF)" % raw_t)
60 
61  def __getFahrenheit__(self):
62  return self.Celsius2Fahrenheit()
63 
64  def __getKelvin__(self):
65  return self.Celsius2Kelvin()
66 
67  def __getHumidity__(self):
68  (raw_t, raw_h) = self.readRawData()
69  if raw_h < 0x3FFF:
70  return raw_h * 1.0 / 2**14
71  else:
72  raise ValueError("Humidity value out of range (RawValue=0x%04X Max:0x3FFF)" % raw_h)
73