busfahrer.py 1.74 KB
Newer Older
Ralf's avatar
Ralf committed
1
from smbus import SMBus
Ralf's avatar
Ralf committed
2
from libtuer import logger
Ralf's avatar
Ralf committed
3
4
from threading import RLock

Ralf's avatar
Ralf committed
5
6
7
8
9
10
11
12
13
class Pin:
	def __init__(self, addr, bit):
		assert 0 <= bit and bit < 8, "There are only 8 bits per byte"
		self.addr = addr
		self.bit  = bit
	
	def __str__(self):
		return "{0:x}.{1}".format(self.addr, self.bit)

Ralf's avatar
Ralf committed
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class I2C:
	'''This class manages the I²C bus.
	It is thread-safe.
	'''
	def __init__(self, bus):
		self._bus = SMBus(bus)
		self._bytes = {} # this maps bytes to the last written value
		self._active = False # for now, we are in initialization mode
		self._lock = RLock()
	
	def activate(self):
		'''This function activates the bus. Only now, stuff is sent to the HW.
		Call this after all relevant pings have default values.'''
		with self._lock:
			self._active = True
			for addr, byte in self._bytes.items():
				self.setPins(addr, byte)
	
	def setPins(self, addr, stateByte):
		'''Set all pins of the given address'''
		with self._lock:
			if self._active:
Ralf's avatar
Ralf committed
36
				#logger.debug("I2C: Setting 0x{:x} to {:08b}".format(addr, stateByte))
Ralf's avatar
Ralf committed
37
38
39
40
41
42
				self._bus.write_byte(addr, stateByte)
			self._bytes[addr] = stateByte
	
	def setPin(self, pin, state):
		'''Set the gien pin: An (address, bit) pair'''
		with self._lock:
Ralf's avatar
Ralf committed
43
			byte = self._bytes.get(pin.addr, 0x00)
Ralf's avatar
Ralf committed
44
45
			# set the bit
			if state:
Ralf's avatar
Ralf committed
46
				byte |= (1 << pin.bit)
Ralf's avatar
Ralf committed
47
			else:
Ralf's avatar
Ralf committed
48
				byte &= ~(1 << pin.bit)
Ralf's avatar
Ralf committed
49
			# now we know what to set
Ralf's avatar
Ralf committed
50
			self.setPins(pin.addr, byte)
Ralf's avatar
Ralf committed
51
	
Ralf's avatar
Ralf committed
52
	def getPins(self, addr):
Ralf's avatar
Ralf committed
53
54
55
		with self._lock:
			if not self._active:
				return None
Ralf's avatar
Ralf committed
56
57
58
59
60
61
62
63
64
			return self._bus.read_byte(addr)
	
	def getPin(self, pin):
		# read the current value
		byte = self.getPins(pin.addr)
		if byte is None: return None
		# now we need to get the bit
		mask = (1 << pin.bit)
		return bool(byte & mask)
Ralf's avatar
Ralf committed
65
66
67


# kate: space-indent off; tab-width 4; indent-width 4;