Yet Another WebIOPi+
 All Classes Namespaces Files Functions Variables Macros Pages
i2c.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 fcntl
16 
17 from webiopi.utils.version import BOARD_REVISION
18 from webiopi.devices.bus import Bus
19 
20 # /dev/i2c-X ioctl commands. The ioctl's parameter is always an
21 # unsigned long, except for:
22 # - I2C_FUNCS, takes pointer to an unsigned long
23 # - I2C_RDWR, takes pointer to struct i2c_rdwr_ioctl_data
24 # - I2C_SMBUS, takes pointer to struct i2c_smbus_ioctl_data
25 
26 I2C_RETRIES = 0x0701 # number of times a device address should
27  # be polled when not acknowledging
28 I2C_TIMEOUT = 0x0702 # set timeout in units of 10 ms
29 
30 # NOTE: Slave address is 7 or 10 bits, but 10-bit addresses
31 # are NOT supported! (due to code brokenness)
32 
33 I2C_SLAVE = 0x0703 # Use this slave address
34 I2C_SLAVE_FORCE = 0x0706 # Use this slave address, even if it
35  # is already in use by a driver!
36 I2C_TENBIT = 0x0704 # 0 for 7 bit addrs, != 0 for 10 bit
37 
38 I2C_FUNCS = 0x0705 # Get the adapter functionality mask
39 
40 I2C_RDWR = 0x0707 # Combined R/W transfer (one STOP only)
41 
42 I2C_PEC = 0x0708 # != 0 to use PEC with SMBus
43 I2C_SMBUS = 0x0720 # SMBus transfer */
44 
45 
46 class I2C(Bus):
47  def __init__(self, slave):
48  self.channel = 0
49  if BOARD_REVISION > 1:
50  self.channel = 1
51 
52  Bus.__init__(self, "I2C", "/dev/i2c-%d" % self.channel)
53  self.slave = slave
54  if fcntl.ioctl(self.fd, I2C_SLAVE, self.slave):
55  raise Exception("Error binding I2C slave 0x%02X" % self.slave)
56 
57  def __str__(self):
58  return "I2C(slave=0x%02X)" % self.slave
59 
60  def readRegister(self, addr):
61  self.writeByte(addr)
62  return self.readByte()
63 
64  def readRegisters(self, addr, count):
65  self.writeByte(addr)
66  return self.readBytes(count)
67 
68  def writeRegister(self, addr, byte):
69  self.writeBytes([addr, byte])
70 
71  def writeRegisters(self, addr, buff):
72  d = bytearray(len(buff)+1)
73  d[0] = addr
74  d[1:] = buff
75  self.writeBytes(d)