e62671845f9121671bbfbe686dde4e4ee35bb7b8
[librfid] / python / pyrfid.c
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <errno.h>
6 #include <libgen.h>
7
8 #include <librfid/rfid.h>
9 #include <librfid/rfid_scan.h>
10 #include <librfid/rfid_reader.h>
11 #include <librfid/rfid_layer2.h>
12 #include <librfid/rfid_protocol.h>
13
14 #include <librfid/rfid_protocol_mifare_classic.h>
15 #include <librfid/rfid_protocol_mifare_ul.h>
16 #include <common.h>
17
18 #include <Python.h>
19 static PyObject *pyi_open(PyObject *self, PyObject *args);
20 static PyObject *pyi_close(PyObject *self, PyObject *args);
21 static PyObject *pyi_rfidscan(PyObject *self, PyObject *args);
22 static PyObject *pyi_rfidlayeropt(PyObject *self, PyObject *args);
23
24 static PyObject *pyi_Error;
25 struct rfid_reader_handle *rh;
26 struct rfid_layer2_handle *l2h;
27 struct rfid_protocol_handle *ph;
28
29 static PyMethodDef pyi_Methods[] = {
30     {"open", pyi_open, METH_VARARGS,
31         "This will initialise the RFID reader"},
32     {"close", pyi_close, METH_VARARGS,
33         "This will close the RFID reader"},
34     {"scan", pyi_rfidscan, METH_VARARGS,
35         "This will scan for any card"},
36     {"get_id", pyi_rfidlayeropt, METH_VARARGS,
37         "This will read the id of the card"},
38     {NULL, NULL, 0, NULL}
39 };
40
41 PyMODINIT_FUNC initpyrfid() {
42     PyObject *m;
43
44     m = Py_InitModule("openpcd", pyi_Methods);
45     pyi_Error = PyErr_NewException("openpcd.error", NULL, NULL);
46     Py_INCREF(pyi_Error);
47     PyModule_AddObject(m, "error", pyi_Error);
48     return;
49 }
50
51 static PyObject *pyi_open(PyObject *self, PyObject *args) {
52     rfid_init();
53     rh = rfid_reader_open(NULL, RFID_READER_OPENPCD);
54     if (!rh)
55         return Py_BuildValue("i", 1);
56     else
57         return Py_BuildValue("i", 0);
58 }
59
60 static PyObject *pyi_close(PyObject *self, PyObject *args) {
61     rfid_reader_close(rh);
62     Py_INCREF(Py_None);
63     return Py_None;
64 }
65
66 static PyObject *pyi_rfidscan(PyObject *self, PyObject *args) {
67     int rc;
68         rc = rfid_scan(rh, &l2h, &ph);
69         return Py_BuildValue("i", rc);
70 }
71
72 static PyObject *pyi_rfidlayeropt(PyObject *self, PyObject *args) {
73                 unsigned char uid_buf[16];
74                 char card_id[16];
75                 unsigned int uid_len = sizeof(uid_buf);
76                 rfid_layer2_getopt(l2h, RFID_OPT_LAYER2_UID, &uid_buf,
77                                    &uid_len);
78                 strcpy(card_id,hexdump(uid_buf, uid_len));
79                 return Py_BuildValue("s", card_id);
80 }