root/i2c-tools/trunk/py-smbus/smbusmodule.c

Revision 6048, 16.3 KB (checked in by khali, 3 weeks ago)

i2c-dev: Move SMBus helper functions to include/i2c/smbus.h

Line 
1/*
2 * smbusmodule.c - Python bindings for Linux SMBus access through i2c-dev
3 * Copyright (C) 2005-2007 Mark M. Hoffman <mhoffman@lightlink.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; version 2 of the License.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17 */
18
19#include <Python.h>
20#include "structmember.h"
21#include <sys/ioctl.h>
22#include <stdlib.h>
23#include <stdio.h>
24#include <fcntl.h>
25#include <linux/i2c.h>
26#include <linux/i2c-dev.h>
27#include <i2c/smbus.h>
28
29/*
30** These are required to build this module against Linux older than 2.6.23.
31*/
32#ifndef I2C_SMBUS_I2C_BLOCK_BROKEN
33#undef I2C_SMBUS_I2C_BLOCK_DATA
34#define I2C_SMBUS_I2C_BLOCK_BROKEN      6
35#define I2C_SMBUS_I2C_BLOCK_DATA        8
36#endif
37
38PyDoc_STRVAR(SMBus_module_doc,
39        "This module defines an object type that allows SMBus transactions\n"
40        "on hosts running the Linux kernel.  The host kernel must have I2C\n"
41        "support, I2C device interface support, and a bus adapter driver.\n"
42        "All of these can be either built-in to the kernel, or loaded from\n"
43        "modules.\n"
44        "\n"
45        "Because the I2C device interface is opened R/W, users of this\n"
46        "module usually must have root permissions.\n");
47
48typedef struct {
49        PyObject_HEAD
50
51        int fd;         /* open file descriptor: /dev/i2c-?, or -1 */
52        int addr;       /* current client SMBus address */
53        int pec;        /* !0 => Packet Error Codes enabled */
54} SMBus;
55
56static PyObject *
57SMBus_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
58{
59        SMBus *self;
60
61        if ((self = (SMBus *)type->tp_alloc(type, 0)) == NULL)
62                return NULL;
63
64        self->fd = -1;
65        self->addr = -1;
66        self->pec = 0;
67
68        return (PyObject *)self;
69}
70
71PyDoc_STRVAR(SMBus_close_doc,
72        "close()\n\n"
73        "Disconnects the object from the bus.\n");
74
75static PyObject *
76SMBus_close(SMBus *self)
77{
78        if ((self->fd != -1) && (close(self->fd) == -1)) {
79                PyErr_SetFromErrno(PyExc_IOError);
80                return NULL;
81        }
82
83        self->fd = -1;
84        self->addr = -1;
85        self->pec = 0;
86
87        Py_INCREF(Py_None);
88        return Py_None;
89}
90
91static void
92SMBus_dealloc(SMBus *self)
93{
94        PyObject *ref = SMBus_close(self);
95        Py_XDECREF(ref);
96
97        self->ob_type->tp_free((PyObject *)self);
98}
99
100#define MAXPATH 16
101
102PyDoc_STRVAR(SMBus_open_doc,
103        "open(bus)\n\n"
104        "Connects the object to the specified SMBus.\n");
105
106static PyObject *
107SMBus_open(SMBus *self, PyObject *args, PyObject *kwds)
108{
109        int bus;
110        char path[MAXPATH];
111
112        static char *kwlist[] = {"bus", NULL};
113
114        if (!PyArg_ParseTupleAndKeywords(args, kwds, "i:open", kwlist, &bus))
115                return NULL;
116
117        if (snprintf(path, MAXPATH, "/dev/i2c-%d", bus) >= MAXPATH) {
118                PyErr_SetString(PyExc_OverflowError,
119                        "Bus number is invalid.");
120                return NULL;
121        }
122
123        if ((self->fd = open(path, O_RDWR, 0)) == -1) {
124                PyErr_SetFromErrno(PyExc_IOError);
125                return NULL;
126        }
127
128        Py_INCREF(Py_None);
129        return Py_None;
130}
131
132static int
133SMBus_init(SMBus *self, PyObject *args, PyObject *kwds)
134{
135        int bus = -1;
136
137        static char *kwlist[] = {"bus", NULL};
138
139        if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:__init__",
140                        kwlist, &bus))
141                return -1;
142
143        if (bus >= 0) {
144                SMBus_open(self, args, kwds);
145                if (PyErr_Occurred())
146                        return -1;
147        }
148
149        return 0;
150}
151
152/*
153 * private helper function, 0 => success, !0 => error
154 */
155static int
156SMBus_set_addr(SMBus *self, int addr)
157{
158        int ret = 0;
159
160        if (self->addr != addr) {
161                ret = ioctl(self->fd, I2C_SLAVE, addr);
162                self->addr = addr;
163        }
164
165        return ret;
166}
167
168#define SMBus_SET_ADDR(self, addr) do { \
169        if (SMBus_set_addr(self, addr)) { \
170                PyErr_SetFromErrno(PyExc_IOError); \
171                return NULL; \
172        } \
173} while(0)
174
175PyDoc_STRVAR(SMBus_write_quick_doc,
176        "write_quick(addr)\n\n"
177        "Perform SMBus Quick transaction.\n");
178
179static PyObject *
180SMBus_write_quick(SMBus *self, PyObject *args)
181{
182        int addr;
183        __s32 result;
184
185        if (!PyArg_ParseTuple(args, "i:write_quick", &addr))
186                return NULL;
187
188        SMBus_SET_ADDR(self, addr);
189
190        if ((result = i2c_smbus_write_quick(self->fd, I2C_SMBUS_WRITE))) {
191                PyErr_SetFromErrno(PyExc_IOError);
192                return NULL;
193        }
194
195        Py_INCREF(Py_None);
196        return Py_None;
197}
198
199PyDoc_STRVAR(SMBus_read_byte_doc,
200        "read_byte(addr) -> result\n\n"
201        "Perform SMBus Read Byte transaction.\n");
202
203static PyObject *
204SMBus_read_byte(SMBus *self, PyObject *args)
205{
206        int addr;
207        __s32 result;
208
209        if (!PyArg_ParseTuple(args, "i:read_byte", &addr))
210                return NULL;
211
212        SMBus_SET_ADDR(self, addr);
213
214        if ((result = i2c_smbus_read_byte(self->fd)) == -1) {
215                PyErr_SetFromErrno(PyExc_IOError);
216                return NULL;
217        }
218
219        return Py_BuildValue("l", (long)result);
220}
221
222PyDoc_STRVAR(SMBus_write_byte_doc,
223        "write_byte(addr, val)\n\n"
224        "Perform SMBus Write Byte transaction.\n");
225
226static PyObject *
227SMBus_write_byte(SMBus *self, PyObject *args)
228{
229        int addr, val;
230        __s32 result;
231
232        if (!PyArg_ParseTuple(args, "ii:write_byte", &addr, &val))
233                return NULL;
234
235        SMBus_SET_ADDR(self, addr);
236
237        if ((result = i2c_smbus_write_byte(self->fd, (__u8)val)) == -1) {
238                PyErr_SetFromErrno(PyExc_IOError);
239                return NULL;
240        }
241
242        Py_INCREF(Py_None);
243        return Py_None;
244}
245
246PyDoc_STRVAR(SMBus_read_byte_data_doc,
247        "read_byte_data(addr, cmd) -> result\n\n"
248        "Perform SMBus Read Byte Data transaction.\n");
249
250static PyObject *
251SMBus_read_byte_data(SMBus *self, PyObject *args)
252{
253        int addr, cmd;
254        __s32 result;
255
256        if (!PyArg_ParseTuple(args, "ii:read_byte_data", &addr, &cmd))
257                return NULL;
258
259        SMBus_SET_ADDR(self, addr);
260
261        if ((result = i2c_smbus_read_byte_data(self->fd, (__u8)cmd)) == -1) {
262                PyErr_SetFromErrno(PyExc_IOError);
263                return NULL;
264        }
265
266        return Py_BuildValue("l", (long)result);
267}
268
269PyDoc_STRVAR(SMBus_write_byte_data_doc,
270        "write_byte_data(addr, cmd, val)\n\n"
271        "Perform SMBus Write Byte Data transaction.\n");
272
273static PyObject *
274SMBus_write_byte_data(SMBus *self, PyObject *args)
275{
276        int addr, cmd, val;
277        __s32 result;
278
279        if (!PyArg_ParseTuple(args, "iii:write_byte_data", &addr, &cmd, &val))
280                return NULL;
281
282        SMBus_SET_ADDR(self, addr);
283
284        if ((result = i2c_smbus_write_byte_data(self->fd,
285                                (__u8)cmd, (__u8)val)) == -1) {
286                PyErr_SetFromErrno(PyExc_IOError);
287                return NULL;
288        }
289
290        Py_INCREF(Py_None);
291        return Py_None;
292}
293
294PyDoc_STRVAR(SMBus_read_word_data_doc,
295        "read_word_data(addr, cmd) -> result\n\n"
296        "Perform SMBus Read Word Data transaction.\n");
297
298static PyObject *
299SMBus_read_word_data(SMBus *self, PyObject *args)
300{
301        int addr, cmd;
302        __s32 result;
303
304        if (!PyArg_ParseTuple(args, "ii:read_word_data", &addr, &cmd))
305                return NULL;
306
307        SMBus_SET_ADDR(self, addr);
308
309        if ((result = i2c_smbus_read_word_data(self->fd, (__u8)cmd)) == -1) {
310                PyErr_SetFromErrno(PyExc_IOError);
311                return NULL;
312        }
313
314        return Py_BuildValue("l", (long)result);
315}
316
317PyDoc_STRVAR(SMBus_write_word_data_doc,
318        "write_word_data(addr, cmd, val)\n\n"
319        "Perform SMBus Write Word Data transaction.\n");
320
321static PyObject *
322SMBus_write_word_data(SMBus *self, PyObject *args)
323{
324        int addr, cmd, val;
325        __s32 result;
326
327        if (!PyArg_ParseTuple(args, "iii:write_word_data", &addr, &cmd, &val))
328                return NULL;
329
330        SMBus_SET_ADDR(self, addr);
331
332        if ((result = i2c_smbus_write_word_data(self->fd,
333                                (__u8)cmd, (__u16)val)) == -1) {
334                PyErr_SetFromErrno(PyExc_IOError);
335                return NULL;
336        }
337
338        Py_INCREF(Py_None);
339        return Py_None;
340}
341
342PyDoc_STRVAR(SMBus_process_call_doc,
343        "process_call(addr, cmd, val)\n\n"
344        "Perform SMBus Process Call transaction.\n");
345
346static PyObject *
347SMBus_process_call(SMBus *self, PyObject *args)
348{
349        int addr, cmd, val;
350        __s32 result;
351
352        if (!PyArg_ParseTuple(args, "iii:process_call", &addr, &cmd, &val))
353                return NULL;
354
355        SMBus_SET_ADDR(self, addr);
356
357        if ((result = i2c_smbus_process_call(self->fd,
358                                (__u8)cmd, (__u16)val)) == -1) {
359                PyErr_SetFromErrno(PyExc_IOError);
360                return NULL;
361        }
362
363        Py_INCREF(Py_None);
364        return Py_None;
365}
366
367/*
368 * private helper function; returns a new list of integers
369 */
370static PyObject *
371SMBus_buf_to_list(__u8 const *buf, int len)
372{
373        PyObject *list = PyList_New(len);
374        int ii;
375
376        if (list == NULL)
377                return NULL;
378
379        for (ii = 0; ii < len; ii++) {
380                PyObject *val = Py_BuildValue("l", (long)buf[ii]);
381                PyList_SET_ITEM(list, ii, val);
382        }
383        return list;
384}
385
386PyDoc_STRVAR(SMBus_read_block_data_doc,
387        "read_block_data(addr, cmd) -> results\n\n"
388        "Perform SMBus Read Block Data transaction.\n");
389
390static PyObject *
391SMBus_read_block_data(SMBus *self, PyObject *args)
392{
393        int addr, cmd;
394        union i2c_smbus_data data;
395
396        if (!PyArg_ParseTuple(args, "ii:read_block_data", &addr, &cmd))
397                return NULL;
398
399        SMBus_SET_ADDR(self, addr);
400
401        /* save a bit of code by calling the access function directly */
402        if (i2c_smbus_access(self->fd, I2C_SMBUS_READ, (__u8)cmd,
403                                I2C_SMBUS_BLOCK_DATA, &data)) {
404                PyErr_SetFromErrno(PyExc_IOError);
405                return NULL;
406        }
407
408        /* first byte of the block contains (remaining) data length */
409        return SMBus_buf_to_list(&data.block[1], data.block[0]);
410}
411
412/*
413 * private helper function: convert an integer list to union i2c_smbus_data
414 */
415static int
416SMBus_list_to_data(PyObject *list, union i2c_smbus_data *data)
417{
418        static char *msg = "Third argument must be a list of at least one, "
419                                "but not more than 32 integers";
420        int ii, len;
421
422        if (!PyList_Check(list)) {
423                PyErr_SetString(PyExc_TypeError, msg);
424                return 0; /* fail */
425        }
426
427        if ((len = PyList_GET_SIZE(list)) > 32) {
428                PyErr_SetString(PyExc_OverflowError, msg);
429                return 0; /* fail */
430        }
431
432        /* first byte is the length */
433        data->block[0] = (__u8)len;
434
435        for (ii = 0; ii < len; ii++) {
436                PyObject *val = PyList_GET_ITEM(list, ii);
437                if (!PyInt_Check(val)) {
438                        PyErr_SetString(PyExc_TypeError, msg);
439                        return 0; /* fail */
440                }
441                data->block[ii+1] = (__u8)PyInt_AS_LONG(val);
442        }
443
444        return 1; /* success */
445}
446
447PyDoc_STRVAR(SMBus_write_block_data_doc,
448        "write_block_data(addr, cmd, [vals])\n\n"
449        "Perform SMBus Write Block Data transaction.\n");
450
451static PyObject *
452SMBus_write_block_data(SMBus *self, PyObject *args)
453{
454        int addr, cmd;
455        union i2c_smbus_data data;
456
457        if (!PyArg_ParseTuple(args, "iiO&:write_block_data", &addr, &cmd,
458                                SMBus_list_to_data, &data))
459                return NULL;
460
461        SMBus_SET_ADDR(self, addr);
462
463        /* save a bit of code by calling the access function directly */
464        if (i2c_smbus_access(self->fd, I2C_SMBUS_WRITE, (__u8)cmd,
465                                I2C_SMBUS_BLOCK_DATA, &data)) {
466                PyErr_SetFromErrno(PyExc_IOError);
467                return NULL;
468        }
469
470        Py_INCREF(Py_None);
471        return Py_None;
472}
473
474PyDoc_STRVAR(SMBus_block_process_call_doc,
475        "block_process_call(addr, cmd, [vals]) -> results\n\n"
476        "Perform SMBus Block Process Call transaction.\n");
477
478static PyObject *
479SMBus_block_process_call(SMBus *self, PyObject *args)
480{
481        int addr, cmd;
482        union i2c_smbus_data data;
483
484        if (!PyArg_ParseTuple(args, "iiO&:block_process_call", &addr, &cmd,
485                        SMBus_list_to_data, &data))
486                return NULL;
487
488        SMBus_SET_ADDR(self, addr);
489
490        /* save a bit of code by calling the access function directly */
491        if (i2c_smbus_access(self->fd, I2C_SMBUS_WRITE, (__u8)cmd,
492                                I2C_SMBUS_BLOCK_PROC_CALL, &data)) {
493                PyErr_SetFromErrno(PyExc_IOError);
494                return NULL;
495        }
496
497        /* first byte of the block contains (remaining) data length */
498        return SMBus_buf_to_list(&data.block[1], data.block[0]);
499}
500
501PyDoc_STRVAR(SMBus_read_i2c_block_data_doc,
502        "read_i2c_block_data(addr, cmd, len=32) -> results\n\n"
503        "Perform I2C Block Read transaction.\n");
504
505static PyObject *
506SMBus_read_i2c_block_data(SMBus *self, PyObject *args)
507{
508        int addr, cmd, len=32;
509        union i2c_smbus_data data;
510
511        if (!PyArg_ParseTuple(args, "ii|i:read_i2c_block_data", &addr, &cmd,
512                        &len))
513                return NULL;
514
515        SMBus_SET_ADDR(self, addr);
516
517        data.block[0] = len;
518        /* save a bit of code by calling the access function directly */
519        if (i2c_smbus_access(self->fd, I2C_SMBUS_READ, (__u8)cmd,
520                                len == 32 ? I2C_SMBUS_I2C_BLOCK_BROKEN:
521                                I2C_SMBUS_I2C_BLOCK_DATA, &data)) {
522                PyErr_SetFromErrno(PyExc_IOError);
523                return NULL;
524        }
525
526        /* first byte of the block contains (remaining) data length */
527        return SMBus_buf_to_list(&data.block[1], data.block[0]);
528}
529
530PyDoc_STRVAR(SMBus_write_i2c_block_data_doc,
531        "write_i2c_block_data(addr, cmd, [vals])\n\n"
532        "Perform I2C Block Write transaction.\n");
533
534static PyObject *
535SMBus_write_i2c_block_data(SMBus *self, PyObject *args)
536{
537        int addr, cmd;
538        union i2c_smbus_data data;
539
540        if (!PyArg_ParseTuple(args, "iiO&:write_i2c_block_data", &addr, &cmd,
541                        SMBus_list_to_data, &data))
542                return NULL;
543
544        SMBus_SET_ADDR(self, addr);
545
546        /* save a bit of code by calling the access function directly */
547        if (i2c_smbus_access(self->fd, I2C_SMBUS_WRITE, (__u8)cmd,
548                                I2C_SMBUS_I2C_BLOCK_BROKEN, &data)) {
549                PyErr_SetFromErrno(PyExc_IOError);
550                return NULL;
551        }
552
553        Py_INCREF(Py_None);
554        return Py_None;
555}
556
557PyDoc_STRVAR(SMBus_type_doc,
558        "SMBus([bus]) -> SMBus\n\n"
559        "Return a new SMBus object that is (optionally) connected to the\n"
560        "specified I2C device interface.\n");
561
562static PyMethodDef SMBus_methods[] = {
563        {"open", (PyCFunction)SMBus_open, METH_VARARGS | METH_KEYWORDS,
564                SMBus_open_doc},
565        {"close", (PyCFunction)SMBus_close, METH_NOARGS,
566                SMBus_close_doc},
567        {"write_quick", (PyCFunction)SMBus_write_quick, METH_VARARGS,
568                SMBus_write_quick_doc},
569        {"read_byte", (PyCFunction)SMBus_read_byte, METH_VARARGS,
570                SMBus_read_byte_doc},
571        {"write_byte", (PyCFunction)SMBus_write_byte, METH_VARARGS,
572                SMBus_write_byte_doc},
573        {"read_byte_data", (PyCFunction)SMBus_read_byte_data, METH_VARARGS,
574                SMBus_read_byte_data_doc},
575        {"write_byte_data", (PyCFunction)SMBus_write_byte_data, METH_VARARGS,
576                SMBus_write_byte_data_doc},
577        {"read_word_data", (PyCFunction)SMBus_read_word_data, METH_VARARGS,
578                SMBus_read_word_data_doc},
579        {"write_word_data", (PyCFunction)SMBus_write_word_data, METH_VARARGS,
580                SMBus_write_word_data_doc},
581        {"process_call", (PyCFunction)SMBus_process_call, METH_VARARGS,
582                SMBus_process_call_doc},
583        {"read_block_data", (PyCFunction)SMBus_read_block_data, METH_VARARGS,
584                SMBus_read_block_data_doc},
585        {"write_block_data", (PyCFunction)SMBus_write_block_data, METH_VARARGS,
586                SMBus_write_block_data_doc},
587        {"block_process_call", (PyCFunction)SMBus_block_process_call,
588                METH_VARARGS, SMBus_block_process_call_doc},
589        {"read_i2c_block_data", (PyCFunction)SMBus_read_i2c_block_data,
590                METH_VARARGS, SMBus_read_i2c_block_data_doc},
591        {"write_i2c_block_data", (PyCFunction)SMBus_write_i2c_block_data,
592                METH_VARARGS, SMBus_write_i2c_block_data_doc},
593        {NULL},
594};
595
596static PyObject *
597SMBus_get_pec(SMBus *self, void *closure)
598{
599        PyObject *result = self->pec ? Py_True : Py_False;
600        Py_INCREF(result);
601        return result;
602}
603
604static int
605SMBus_set_pec(SMBus *self, PyObject *val, void *closure)
606{
607        int pec;
608
609        pec = PyObject_IsTrue(val);
610
611        if (val == NULL) {
612                PyErr_SetString(PyExc_TypeError,
613                        "Cannot delete attribute");
614                return -1;
615        }
616        else if (pec == -1) {
617                PyErr_SetString(PyExc_TypeError, 
618                        "The pec attribute must be a boolean.");
619                return -1;
620        }
621
622        if (self->pec != pec) {
623                if (ioctl(self->fd, I2C_PEC, pec)) {
624                        PyErr_SetFromErrno(PyExc_IOError);
625                        return -1;
626                }
627                self->pec = pec;
628        }
629
630        return 0;
631}
632
633static PyGetSetDef SMBus_getset[] = {
634        {"pec", (getter)SMBus_get_pec, (setter)SMBus_set_pec,
635                        "True if Packet Error Codes (PEC) are enabled"},
636        {NULL},
637};
638
639static PyTypeObject SMBus_type = {
640        PyObject_HEAD_INIT(NULL)
641        0,                              /* ob_size */
642        "SMBus",                        /* tp_name */
643        sizeof(SMBus),                  /* tp_basicsize */
644        0,                              /* tp_itemsize */
645        (destructor)SMBus_dealloc,      /* tp_dealloc */
646        0,                              /* tp_print */
647        0,                              /* tp_getattr */
648        0,                              /* tp_setattr */
649        0,                              /* tp_compare */
650        0,                              /* tp_repr */
651        0,                              /* tp_as_number */
652        0,                              /* tp_as_sequence */
653        0,                              /* tp_as_mapping */
654        0,                              /* tp_hash */
655        0,                              /* tp_call */
656        0,                              /* tp_str */
657        0,                              /* tp_getattro */
658        0,                              /* tp_setattro */
659        0,                              /* tp_as_buffer */
660        Py_TPFLAGS_DEFAULT,             /* tp_flags */
661        SMBus_type_doc,                 /* tp_doc */
662        0,                              /* tp_traverse */
663        0,                              /* tp_clear */
664        0,                              /* tp_richcompare */
665        0,                              /* tp_weaklistoffset */
666        0,                              /* tp_iter */
667        0,                              /* tp_iternext */
668        SMBus_methods,                  /* tp_methods */
669        0,                              /* tp_members */
670        SMBus_getset,                   /* tp_getset */
671        0,                              /* tp_base */
672        0,                              /* tp_dict */
673        0,                              /* tp_descr_get */
674        0,                              /* tp_descr_set */
675        0,                              /* tp_dictoffset */
676        (initproc)SMBus_init,           /* tp_init */
677        0,                              /* tp_alloc */
678        SMBus_new,                      /* tp_new */
679};
680
681static PyMethodDef SMBus_module_methods[] = {
682        {NULL}
683};
684
685#ifndef PyMODINIT_FUNC  /* declarations for DLL import/export */
686#define PyMODINIT_FUNC void
687#endif
688PyMODINIT_FUNC
689initsmbus(void) 
690{
691        PyObject* m;
692
693        if (PyType_Ready(&SMBus_type) < 0)
694                return;
695
696        m = Py_InitModule3("smbus", SMBus_module_methods, SMBus_module_doc);
697
698        Py_INCREF(&SMBus_type);
699        PyModule_AddObject(m, "SMBus", (PyObject *)&SMBus_type);
700}
701
Note: See TracBrowser for help on using the browser.