Yet Another WebIOPi+
 All Classes Namespaces Files Functions Variables Macros Pages
onewire.py
Go to the documentation of this file.
1 # Copyright 2012-2013 Eric Ptak - trouch.com
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 import os
16 from webiopi.devices.bus import Bus, loadModule
17 
18 EXTRAS = {
19  "TEMP": {"loaded": False, "module": "w1-therm"},
20  "2408": {"loaded": False, "module": "w1_ds2408"}
21 
22 }
23 
24 def loadExtraModule(name):
25  if EXTRAS[name]["loaded"] == False:
26  loadModule(EXTRAS[name]["module"])
27  EXTRAS[name]["loaded"] = True
28 
29 class OneWire(Bus):
30  def __init__(self, slave=None, family=0, extra=None):
31  Bus.__init__(self, "ONEWIRE", "/sys/bus/w1/devices/w1_bus_master1/w1_master_slaves", os.O_RDONLY)
32  if self.fd > 0:
33  os.close(self.fd)
34  self.fd = 0
35 
36  self.family = family
37  if slave != None:
38  addr = slave.split("-")
39  if len(addr) == 1:
40  self.slave = "%02x-%s" % (family, slave)
41  elif len(addr) == 2:
42  prefix = int(addr[0], 16)
43  if family > 0 and family != prefix:
44  raise Exception("1-Wire slave address %s does not match family %02x" % (slave, family))
45  self.slave = slave
46  else:
47  devices = self.deviceList()
48  if len(devices) == 0:
49  raise Exception("No device match family %02x" % family)
50  self.slave = devices[0]
51 
52  loadExtraModule(extra)
53 
54  def __str__(self):
55  return "1-Wire(slave=%s)" % self.slave
56 
57  def deviceList(self):
58  devices = []
59  with open(self.device) as f:
60  lines = f.read().split("\n")
61  if self.family > 0:
62  prefix = "%02x-" % self.family
63  for line in lines:
64  if line.startswith(prefix):
65  devices.append(line)
66  else:
67  devices = lines
68  return devices;
69 
70  def read(self):
71  with open("/sys/bus/w1/devices/%s/w1_slave" % self.slave) as f:
72  data = f.read()
73  return data
74 
def loadModule
Definition: bus.py:28