added teleop, move_base for cmd_vel
[ros_wild_thumper.git] / scripts / i2c.py
1 #!/usr/bin/env python
2 # -*- coding: iso-8859-15 -*-
3
4 import threading
5 import inspect
6 import os
7 import logging
8 from ctypes import *
9 from time import sleep
10
11 DEBUG=0
12 logger = logging.getLogger(__name__)
13
14 class i2c:
15         libc = CDLL("libc.so.6")
16         I2C_SLAVE = 0x0703  # Use this slave address
17         __single = None
18         __lock = threading.Lock()
19         __parent_owner = None
20
21         def __init__(self, addr):
22                 with i2c.__lock:
23                         count = 0
24                         while(i2c.__single):
25                                 parent = inspect.stack()[1][3]
26                                 count += 1
27                                 sleep(0.001)
28                         if DEBUG:
29                                 if count > 10:
30                                         parent_owner = "%s (%d), %s()" % (self.__parent_owner[1], self.__parent_owner[2], self.__parent_owner[3])
31                                         logger.warning("Error: (%s) I2C blocked %fs by %s!", parent, count*0.001, parent_owner)
32                                 i2c.__parent_owner = inspect.stack()[1]
33                         i2c.__single = True
34                 self.dev = i2c.libc.open("/dev/i2c-2", os.O_RDWR)
35                 if self.dev < 0:
36                         raise IOError("open")
37                 err = i2c.libc.ioctl(self.dev, i2c.I2C_SLAVE, addr>>1)
38                 if err < 0:
39                         raise IOError("ioctl")
40
41         def write(self, s):
42                 num_write = i2c.libc.write(self.dev, s, len(s))
43                 if num_write != len(s):
44                         self.close()
45                         raise IOError("write: %d" % (num_write))
46         
47         def read(self, num):
48                 buf = create_string_buffer(num)
49                 num_read = i2c.libc.read(self.dev, buf, num)
50                 if num_read != num:
51                         self.close()
52                         raise IOError("read: %d" % (num_read))
53                 return buf.raw
54
55         def close(self):
56                 if self.dev:
57                         i2c.libc.close(self.dev)
58                         self.dev = None
59                         #i2c.__parent_owner = None
60                         i2c.__single = None
61
62         def __del__(self):
63                 self.close()
64
65 if __name__ == "__main__":
66         import struct
67         import sys
68
69         dev = i2c(0x50)
70         s = struct.pack(">Bh", int(sys.argv[1]), int(sys.argv[2]))
71         dev.write(s)
72         dev.close()