Debian Codegraph @

source/py_gpio.c

raw symbols SCIP
1 /*
2 Copyright (c) 2012-2021 Ben Croston
3
4 Permission is hereby granted, free of charge, to any person obtaining a copy of
5 this software and associated documentation files (the "Software"), to deal in
6 the Software without restriction, including without limitation the rights to
7 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
8 of the Software, and to permit persons to whom the Software is furnished to do
9 so, subject to the following conditions:
10
11 The above copyright notice and this permission notice shall be included in all
12 copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 SOFTWARE.
21 */
22
23 #include "Python.h"
24 #include "c_gpio.h"
25 #include "event_gpio.h"
26 #include "py_pwm.h"
27 #include "cpuinfo.h"
28 #include "constants.h"
29 #include "common.h"
30
31 static PyObject *rpi_revision; // deprecated
32 static PyObject *board_info;
33 static int gpio_warnings = 1;
34
35 struct py_callback
36 {
37 unsigned int gpio;
38 PyObject *py_cb;
39 struct py_callback *next;
40 };
41 static struct py_callback *py_callbacks = NULL;
42
43 static int mmap_gpio_mem(void)
44 {
45 int result;
46
47 if (module_setup)
48 return 0;
49
50 result = setup();
51 if (result == SETUP_DEVMEM_FAIL)
52 {
53 PyErr_SetString(PyExc_RuntimeError, "No access to /dev/mem. Try running as root!");
54 return 1;
55 } else if (result == SETUP_MALLOC_FAIL) {
56 PyErr_NoMemory();
57 return 2;
58 } else if (result == SETUP_MMAP_FAIL) {
59 PyErr_SetString(PyExc_RuntimeError, "Mmap of GPIO registers failed");
60 return 3;
61 } else if (result == SETUP_CPUINFO_FAIL) {
62 PyErr_SetString(PyExc_RuntimeError, "Unable to open /proc/cpuinfo");
63 return 4;
64 } else if (result == SETUP_NO_PERI_ADDR) {
65 PyErr_SetString(PyExc_RuntimeError, "Cannot determine SOC peripheral base address");
66 return 5;
67 } else { // result == SETUP_OK
68 module_setup = 1;
69 return 0;
70 }
71 }
72
73 // python function cleanup(channel=None)
74 static PyObject *py_cleanup(PyObject *self, PyObject *args, PyObject *kwargs)
75 {
76 int i;
77 int chancount = -666;
78 int found = 0;
79 int channel = -666;
80 unsigned int gpio;
81 PyObject *chanlist = NULL;
82 PyObject *chantuple = NULL;
83 PyObject *tempobj;
84 static char *kwlist[] = {"channel", NULL};
85
86 void cleanup_one(void)
87 {
88 // clean up any /sys/class exports
89 event_cleanup(gpio);
90
91 // set everything back to input
92 if (gpio_direction[gpio] != -1) {
93 setup_gpio(gpio, INPUT, PUD_OFF);
94 gpio_direction[gpio] = -1;
95 found = 1;
96 }
97 }
98
99 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist, &chanlist))
100 return NULL;
101
102 if (chanlist == NULL) { // channel kwarg not set
103 // do nothing
104 #if PY_MAJOR_VERSION > 2
105 } else if (PyLong_Check(chanlist)) {
106 channel = (int)PyLong_AsLong(chanlist);
107 #else
108 } else if (PyInt_Check(chanlist)) {
109 channel = (int)PyInt_AsLong(chanlist);
110 #endif
111 if (PyErr_Occurred())
112 return NULL;
113 chanlist = NULL;
114 } else if (PyList_Check(chanlist)) {
115 chancount = PyList_Size(chanlist);
116 } else if (PyTuple_Check(chanlist)) {
117 chantuple = chanlist;
118 chanlist = NULL;
119 chancount = PyTuple_Size(chantuple);
120 } else {
121 // raise exception
122 PyErr_SetString(PyExc_ValueError, "Channel must be an integer or list/tuple of integers");
123 return NULL;
124 }
125
126 if (module_setup && !setup_error) {
127 if (channel == -666 && chancount == -666) { // channel not set - cleanup everything
128 // clean up any /sys/class exports
129 event_cleanup_all();
130
131 // set everything back to input
132 for (i=0; i<54; i++) {
133 if (gpio_direction[i] != -1) {
134 setup_gpio(i, INPUT, PUD_OFF);
135 gpio_direction[i] = -1;
136 found = 1;
137 }
138 }
139 gpio_mode = MODE_UNKNOWN;
140 } else if (channel != -666) { // channel was an int indicating single channel
141 if (get_gpio_number(channel, &gpio))
142 return NULL;
143 cleanup_one();
144 } else { // channel was a list/tuple
145 for (i=0; i<chancount; i++) {
146 if (chanlist) {
147 if ((tempobj = PyList_GetItem(chanlist, i)) == NULL) {
148 return NULL;
149 }
150 } else { // assume chantuple
151 if ((tempobj = PyTuple_GetItem(chantuple, i)) == NULL) {
152 return NULL;
153 }
154 }
155
156 #if PY_MAJOR_VERSION > 2
157 if (PyLong_Check(tempobj)) {
158 channel = (int)PyLong_AsLong(tempobj);
159 #else
160 if (PyInt_Check(tempobj)) {
161 channel = (int)PyInt_AsLong(tempobj);
162 #endif
163 if (PyErr_Occurred())
164 return NULL;
165 } else {
166 PyErr_SetString(PyExc_ValueError, "Channel must be an integer");
167 return NULL;
168 }
169
170 if (get_gpio_number(channel, &gpio))
171 return NULL;
172 cleanup_one();
173 }
174 }
175 }
176
177 // check if any channels set up - if not warn about misuse of GPIO.cleanup()
178 if (!found && gpio_warnings) {
179 PyErr_WarnEx(NULL, "No channels have been set up yet - nothing to clean up! Try cleaning up at the end of your program instead!", 1);
180 }
181
182 Py_RETURN_NONE;
183 }
184
185 // python function setup(channel(s), direction, pull_up_down=PUD_OFF, initial=None)
186 static PyObject *py_setup_channel(PyObject *self, PyObject *args, PyObject *kwargs)
187 {
188 unsigned int gpio;
189 int channel = -1;
190 int direction;
191 int i, chancount;
192 PyObject *chanlist = NULL;
193 PyObject *chantuple = NULL;
194 PyObject *tempobj;
195 int pud = PUD_OFF + PY_PUD_CONST_OFFSET;
196 int initial = -1;
197 static char *kwlist[] = {"channel", "direction", "pull_up_down", "initial", NULL};
198 int func;
199
200 int setup_one(void) {
201 if (get_gpio_number(channel, &gpio))
202 return 0;
203
204 func = gpio_function(gpio);
205 if (gpio_warnings && // warnings enabled and
206 ((func != 0 && func != 1) || // (already one of the alt functions or
207 (gpio_direction[gpio] == -1 && func == 1))) // already an output not set from this program)
208 {
209 PyErr_WarnEx(NULL, "This channel is already in use, continuing anyway. Use GPIO.setwarnings(False) to disable warnings.", 1);
210 }
211
212 // warn about pull/up down on i2c channels
213 if (gpio_warnings) {
214 if (rpiinfo.p1_revision == 0) { // compute module - do nothing
215 } else if ((rpiinfo.p1_revision == 1 && (gpio == 0 || gpio == 1)) ||
216 (gpio == 2 || gpio == 3)) {
217 if (pud == PUD_UP || pud == PUD_DOWN)
218 PyErr_WarnEx(NULL, "A physical pull up resistor is fitted on this channel!", 1);
219 }
220 }
221
222 if (direction == OUTPUT && (initial == LOW || initial == HIGH)) {
223 output_gpio(gpio, initial);
224 }
225 setup_gpio(gpio, direction, pud);
226 gpio_direction[gpio] = direction;
227 return 1;
228 }
229
230 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Oi|ii", kwlist, &chanlist, &direction, &pud, &initial))
231 return NULL;
232
233 #if PY_MAJOR_VERSION > 2
234 if (PyLong_Check(chanlist)) {
235 channel = (int)PyLong_AsLong(chanlist);
236 #else
237 if (PyInt_Check(chanlist)) {
238 channel = (int)PyInt_AsLong(chanlist);
239 #endif
240 if (PyErr_Occurred())
241 return NULL;
242 chanlist = NULL;
243 } else if (PyList_Check(chanlist)) {
244 // do nothing
245 } else if (PyTuple_Check(chanlist)) {
246 chantuple = chanlist;
247 chanlist = NULL;
248 } else {
249 // raise exception
250 PyErr_SetString(PyExc_ValueError, "Channel must be an integer or list/tuple of integers");
251 return NULL;
252 }
253
254 // check module has been imported cleanly
255 if (setup_error)
256 {
257 PyErr_SetString(PyExc_RuntimeError, "Module not imported correctly!");
258 return NULL;
259 }
260
261 if (mmap_gpio_mem())
262 return NULL;
263
264 if (direction != INPUT && direction != OUTPUT) {
265 PyErr_SetString(PyExc_ValueError, "An invalid direction was passed to setup()");
266 return 0;
267 }
268
269 if (direction == OUTPUT && pud != PUD_OFF + PY_PUD_CONST_OFFSET) {
270 PyErr_SetString(PyExc_ValueError, "pull_up_down parameter is not valid for outputs");
271 return 0;
272 }
273
274 if (direction == INPUT && initial != -1) {
275 PyErr_SetString(PyExc_ValueError, "initial parameter is not valid for inputs");
276 return 0;
277 }
278
279 if (direction == OUTPUT)
280 pud = PUD_OFF + PY_PUD_CONST_OFFSET;
281
282 pud -= PY_PUD_CONST_OFFSET;
283 if (pud != PUD_OFF && pud != PUD_DOWN && pud != PUD_UP) {
284 PyErr_SetString(PyExc_ValueError, "Invalid value for pull_up_down - should be either PUD_OFF, PUD_UP or PUD_DOWN");
285 return NULL;
286 }
287
288 if (chanlist) {
289 chancount = PyList_Size(chanlist);
290 } else if (chantuple) {
291 chancount = PyTuple_Size(chantuple);
292 } else {
293 if (!setup_one())
294 return NULL;
295 Py_RETURN_NONE;
296 }
297
298 for (i=0; i<chancount; i++) {
299 if (chanlist) {
300 if ((tempobj = PyList_GetItem(chanlist, i)) == NULL) {
301 return NULL;
302 }
303 } else { // assume chantuple
304 if ((tempobj = PyTuple_GetItem(chantuple, i)) == NULL) {
305 return NULL;
306 }
307 }
308
309 #if PY_MAJOR_VERSION > 2
310 if (PyLong_Check(tempobj)) {
311 channel = (int)PyLong_AsLong(tempobj);
312 #else
313 if (PyInt_Check(tempobj)) {
314 channel = (int)PyInt_AsLong(tempobj);
315 #endif
316 if (PyErr_Occurred())
317 return NULL;
318 } else {
319 PyErr_SetString(PyExc_ValueError, "Channel must be an integer");
320 return NULL;
321 }
322
323 if (!setup_one())
324 return NULL;
325 }
326
327 Py_RETURN_NONE;
328 }
329
330 // python function output(channel(s), value(s))
331 static PyObject *py_output_gpio(PyObject *self, PyObject *args)
332 {
333 unsigned int gpio;
334 int channel = -1;
335 int value = -1;
336 int i;
337 PyObject *chanlist = NULL;
338 PyObject *valuelist = NULL;
339 PyObject *chantuple = NULL;
340 PyObject *valuetuple = NULL;
341 PyObject *tempobj = NULL;
342 int chancount = -1;
343 int valuecount = -1;
344
345 int output(void) {
346 if (get_gpio_number(channel, &gpio))
347 return 0;
348
349 if (gpio_direction[gpio] != OUTPUT)
350 {
351 PyErr_SetString(PyExc_RuntimeError, "The GPIO channel has not been set up as an OUTPUT");
352 return 0;
353 }
354
355 if (check_gpio_priv())
356 return 0;
357
358 output_gpio(gpio, value);
359 return 1;
360 }
361
362 if (!PyArg_ParseTuple(args, "OO", &chanlist, &valuelist))
363 return NULL;
364
365 #if PY_MAJOR_VERSION >= 3
366 if (PyLong_Check(chanlist)) {
367 channel = (int)PyLong_AsLong(chanlist);
368 #else
369 if (PyInt_Check(chanlist)) {
370 channel = (int)PyInt_AsLong(chanlist);
371 #endif
372 if (PyErr_Occurred())
373 return NULL;
374 chanlist = NULL;
375 } else if (PyList_Check(chanlist)) {
376 // do nothing
377 } else if (PyTuple_Check(chanlist)) {
378 chantuple = chanlist;
379 chanlist = NULL;
380 } else {
381 PyErr_SetString(PyExc_ValueError, "Channel must be an integer or list/tuple of integers");
382 return NULL;
383 }
384
385 #if PY_MAJOR_VERSION >= 3
386 if (PyLong_Check(valuelist)) {
387 value = (int)PyLong_AsLong(valuelist);
388 #else
389 if (PyInt_Check(valuelist)) {
390 value = (int)PyInt_AsLong(valuelist);
391 #endif
392 if (PyErr_Occurred())
393 return NULL;
394 valuelist = NULL;
395 } else if (PyList_Check(valuelist)) {
396 // do nothing
397 } else if (PyTuple_Check(valuelist)) {
398 valuetuple = valuelist;
399 valuelist = NULL;
400 } else {
401 PyErr_SetString(PyExc_ValueError, "Value must be an integer/boolean or a list/tuple of integers/booleans");
402 return NULL;
403 }
404
405 if (chanlist)
406 chancount = PyList_Size(chanlist);
407 if (chantuple)
408 chancount = PyTuple_Size(chantuple);
409 if (valuelist)
410 valuecount = PyList_Size(valuelist);
411 if (valuetuple)
412 valuecount = PyTuple_Size(valuetuple);
413 if ((chancount != -1 && chancount != valuecount && valuecount != -1) || (chancount == -1 && valuecount != -1)) {
414 PyErr_SetString(PyExc_RuntimeError, "Number of channels != number of values");
415 return NULL;
416 }
417
418 if (chancount == -1) {
419 if (!output())
420 return NULL;
421 Py_RETURN_NONE;
422 }
423
424 for (i=0; i<chancount; i++) {
425 // get channel number
426 if (chanlist) {
427 if ((tempobj = PyList_GetItem(chanlist, i)) == NULL) {
428 return NULL;
429 }
430 } else { // assume chantuple
431 if ((tempobj = PyTuple_GetItem(chantuple, i)) == NULL) {
432 return NULL;
433 }
434 }
435
436 #if PY_MAJOR_VERSION >= 3
437 if (PyLong_Check(tempobj)) {
438 channel = (int)PyLong_AsLong(tempobj);
439 #else
440 if (PyInt_Check(tempobj)) {
441 channel = (int)PyInt_AsLong(tempobj);
442 #endif
443 if (PyErr_Occurred())
444 return NULL;
445 } else {
446 PyErr_SetString(PyExc_ValueError, "Channel must be an integer");
447 return NULL;
448 }
449
450 // get value
451 if (valuecount > 0) {
452 if (valuelist) {
453 if ((tempobj = PyList_GetItem(valuelist, i)) == NULL) {
454 return NULL;
455 }
456 } else { // assume valuetuple
457 if ((tempobj = PyTuple_GetItem(valuetuple, i)) == NULL) {
458 return NULL;
459 }
460 }
461 #if PY_MAJOR_VERSION >= 3
462 if (PyLong_Check(tempobj)) {
463 value = (int)PyLong_AsLong(tempobj);
464 #else
465 if (PyInt_Check(tempobj)) {
466 value = (int)PyInt_AsLong(tempobj);
467 #endif
468 if (PyErr_Occurred())
469 return NULL;
470 } else {
471 PyErr_SetString(PyExc_ValueError, "Value must be an integer or boolean");
472 return NULL;
473 }
474 }
475 if (!output())
476 return NULL;
477 }
478
479 Py_RETURN_NONE;
480 }
481
482 // python function value = input(channel)
483 static PyObject *py_input_gpio(PyObject *self, PyObject *args)
484 {
485 unsigned int gpio;
486 int channel;
487 PyObject *value;
488
489 if (!PyArg_ParseTuple(args, "i", &channel))
490 return NULL;
491
492 if (get_gpio_number(channel, &gpio))
493 return NULL;
494
495 // check channel is set up as an input or output
496 if (gpio_direction[gpio] != INPUT && gpio_direction[gpio] != OUTPUT)
497 {
498 PyErr_SetString(PyExc_RuntimeError, "You must setup() the GPIO channel first");
499 return NULL;
500 }
501
502 if (check_gpio_priv())
503 return NULL;
504
505 if (input_gpio(gpio)) {
506 value = Py_BuildValue("i", HIGH);
507 } else {
508 value = Py_BuildValue("i", LOW);
509 }
510 return value;
511 }
512
513 // python function setmode(mode)
514 static PyObject *py_setmode(PyObject *self, PyObject *args)
515 {
516 int new_mode;
517
518 if (!PyArg_ParseTuple(args, "i", &new_mode))
519 return NULL;
520
521 if (gpio_mode != MODE_UNKNOWN && new_mode != gpio_mode)
522 {
523 PyErr_SetString(PyExc_ValueError, "A different mode has already been set!");
524 return NULL;
525 }
526
527 if (setup_error)
528 {
529 PyErr_SetString(PyExc_RuntimeError, "Module not imported correctly!");
530 return NULL;
531 }
532
533 if (new_mode != BOARD && new_mode != BCM)
534 {
535 PyErr_SetString(PyExc_ValueError, "An invalid mode was passed to setmode()");
536 return NULL;
537 }
538
539 if (rpiinfo.p1_revision == 0 && new_mode == BOARD)
540 {
541 PyErr_SetString(PyExc_RuntimeError, "BOARD numbering system not applicable on compute module");
542 return NULL;
543 }
544
545 gpio_mode = new_mode;
546 Py_RETURN_NONE;
547 }
548
549 // python function getmode()
550 static PyObject *py_getmode(PyObject *self, PyObject *args)
551 {
552 PyObject *value;
553
554 if (setup_error)
555 {
556 PyErr_SetString(PyExc_RuntimeError, "Module not imported correctly!");
557 return NULL;
558 }
559
560 if (gpio_mode == MODE_UNKNOWN)
561 Py_RETURN_NONE;
562
563 value = Py_BuildValue("i", gpio_mode);
564 return value;
565 }
566
567 static unsigned int chan_from_gpio(unsigned int gpio)
568 {
569 int chan;
570 int chans;
571
572 if (gpio_mode == BCM)
573 return gpio;
574 if (rpiinfo.p1_revision == 0) // not applicable for compute module
575 return -1;
576 else if (rpiinfo.p1_revision == 1 || rpiinfo.p1_revision == 2)
577 chans = 26;
578 else
579 chans = 40;
580 for (chan=1; chan<=chans; chan++)
581 if (*(*pin_to_gpio+chan) == (int)gpio)
582 return chan;
583 return -1;
584 }
585
586 static void run_py_callbacks(unsigned int gpio)
587 {
588 PyObject *result;
589 PyGILState_STATE gstate;
590 struct py_callback *cb = py_callbacks;
591
592 while (cb != NULL)
593 {
594 if (cb->gpio == gpio) {
595 // run callback
596 gstate = PyGILState_Ensure();
597 result = PyObject_CallFunction(cb->py_cb, "i", chan_from_gpio(gpio));
598 if (result == NULL && PyErr_Occurred()){
599 PyErr_Print();
600 PyErr_Clear();
601 }
602 Py_XDECREF(result);
603 PyGILState_Release(gstate);
604 }
605 cb = cb->next;
606 }
607 }
608
609 static int add_py_callback(unsigned int gpio, PyObject *cb_func)
610 {
611 struct py_callback *new_py_cb;
612 struct py_callback *cb = py_callbacks;
613
614 // add callback to py_callbacks list
615 new_py_cb = malloc(sizeof(struct py_callback));
616 if (new_py_cb == 0)
617 {
618 PyErr_NoMemory();
619 return -1;
620 }
621 new_py_cb->py_cb = cb_func;
622 Py_XINCREF(cb_func); // Add a reference to new callback
623 new_py_cb->gpio = gpio;
624 new_py_cb->next = NULL;
625 if (py_callbacks == NULL) {
626 py_callbacks = new_py_cb;
627 } else {
628 // add to end of list
629 while (cb->next != NULL)
630 cb = cb->next;
631 cb->next = new_py_cb;
632 }
633 add_edge_callback(gpio, run_py_callbacks);
634 return 0;
635 }
636
637 // python function add_event_callback(gpio, callback)
638 static PyObject *py_add_event_callback(PyObject *self, PyObject *args, PyObject *kwargs)
639 {
640 unsigned int gpio;
641 int channel;
642 PyObject *cb_func;
643 char *kwlist[] = {"gpio", "callback", NULL};
644
645 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "iO|i", kwlist, &channel, &cb_func))
646 return NULL;
647
648 if (!PyCallable_Check(cb_func))
649 {
650 PyErr_SetString(PyExc_TypeError, "Parameter must be callable");
651 return NULL;
652 }
653
654 if (get_gpio_number(channel, &gpio))
655 return NULL;
656
657 // check channel is set up as an input
658 if (gpio_direction[gpio] != INPUT)
659 {
660 PyErr_SetString(PyExc_RuntimeError, "You must setup() the GPIO channel as an input first");
661 return NULL;
662 }
663
664 if (!gpio_event_added(gpio))
665 {
666 PyErr_SetString(PyExc_RuntimeError, "Add event detection using add_event_detect first before adding a callback");
667 return NULL;
668 }
669
670 if (add_py_callback(gpio, cb_func) != 0)
671 return NULL;
672
673 Py_RETURN_NONE;
674 }
675
676 // python function add_event_detect(gpio, edge, callback=None, bouncetime=None)
677 static PyObject *py_add_event_detect(PyObject *self, PyObject *args, PyObject *kwargs)
678 {
679 unsigned int gpio;
680 int channel, edge, result;
681 int bouncetime = -666;
682 PyObject *cb_func = NULL;
683 char *kwlist[] = {"gpio", "edge", "callback", "bouncetime", NULL};
684
685 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ii|Oi", kwlist, &channel, &edge, &cb_func, &bouncetime))
686 return NULL;
687
688 if (cb_func != NULL && !PyCallable_Check(cb_func))
689 {
690 PyErr_SetString(PyExc_TypeError, "Parameter must be callable");
691 return NULL;
692 }
693
694 if (get_gpio_number(channel, &gpio))
695 return NULL;
696
697 // check channel is set up as an input
698 if (gpio_direction[gpio] != INPUT)
699 {
700 PyErr_SetString(PyExc_RuntimeError, "You must setup() the GPIO channel as an input first");
701 return NULL;
702 }
703
704 // is edge valid value
705 edge -= PY_EVENT_CONST_OFFSET;
706 if (edge != RISING_EDGE && edge != FALLING_EDGE && edge != BOTH_EDGE)
707 {
708 PyErr_SetString(PyExc_ValueError, "The edge must be set to RISING, FALLING or BOTH");
709 return NULL;
710 }
711
712 if (bouncetime <= 0 && bouncetime != -666)
713 {
714 PyErr_SetString(PyExc_ValueError, "Bouncetime must be greater than 0");
715 return NULL;
716 }
717
718 if (check_gpio_priv())
719 return NULL;
720
721 if ((result = add_edge_detect(gpio, edge, bouncetime)) != 0) // starts a thread
722 {
723 if (result == 1)
724 {
725 PyErr_SetString(PyExc_RuntimeError, "Conflicting edge detection already enabled for this GPIO channel");
726 return NULL;
727 } else {
728 PyErr_SetString(PyExc_RuntimeError, "Failed to add edge detection");
729 return NULL;
730 }
731 }
732
733 if (cb_func != NULL)
734 if (add_py_callback(gpio, cb_func) != 0)
735 return NULL;
736
737 Py_RETURN_NONE;
738 }
739
740 // python function remove_event_detect(gpio)
741 static PyObject *py_remove_event_detect(PyObject *self, PyObject *args)
742 {
743 unsigned int gpio;
744 int channel;
745 struct py_callback *cb = py_callbacks;
746 struct py_callback *temp;
747 struct py_callback *prev = NULL;
748
749 if (!PyArg_ParseTuple(args, "i", &channel))
750 return NULL;
751
752 if (get_gpio_number(channel, &gpio))
753 return NULL;
754
755 // remove all python callbacks for gpio
756 while (cb != NULL)
757 {
758 if (cb->gpio == gpio)
759 {
760 Py_XDECREF(cb->py_cb);
761 if (prev == NULL)
762 py_callbacks = cb->next;
763 else
764 prev->next = cb->next;
765 temp = cb;
766 cb = cb->next;
767 free(temp);
768 } else {
769 prev = cb;
770 cb = cb->next;
771 }
772 }
773
774 if (check_gpio_priv())
775 return NULL;
776
777 remove_edge_detect(gpio);
778
779 Py_RETURN_NONE;
780 }
781
782 // python function value = event_detected(channel)
783 static PyObject *py_event_detected(PyObject *self, PyObject *args)
784 {
785 unsigned int gpio;
786 int channel;
787
788 if (!PyArg_ParseTuple(args, "i", &channel))
789 return NULL;
790
791 if (get_gpio_number(channel, &gpio))
792 return NULL;
793
794 if (event_detected(gpio))
795 Py_RETURN_TRUE;
796 else
797 Py_RETURN_FALSE;
798 }
799
800 // python function channel = wait_for_edge(channel, edge, bouncetime=None, timeout=None)
801 static PyObject *py_wait_for_edge(PyObject *self, PyObject *args, PyObject *kwargs)
802 {
803 unsigned int gpio;
804 int channel, edge, result;
805 int bouncetime = -666; // None
806 int timeout = -1; // None
807
808 static char *kwlist[] = {"channel", "edge", "bouncetime", "timeout", NULL};
809
810 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ii|ii", kwlist, &channel, &edge, &bouncetime, &timeout))
811 return NULL;
812
813 if (get_gpio_number(channel, &gpio))
814 return NULL;
815
816 // check channel is setup as an input
817 if (gpio_direction[gpio] != INPUT)
818 {
819 PyErr_SetString(PyExc_RuntimeError, "You must setup() the GPIO channel as an input first");
820 return NULL;
821 }
822
823 // is edge a valid value?
824 edge -= PY_EVENT_CONST_OFFSET;
825 if (edge != RISING_EDGE && edge != FALLING_EDGE && edge != BOTH_EDGE)
826 {
827 PyErr_SetString(PyExc_ValueError, "The edge must be set to RISING, FALLING or BOTH");
828 return NULL;
829 }
830
831 if (bouncetime <= 0 && bouncetime != -666)
832 {
833 PyErr_SetString(PyExc_ValueError, "Bouncetime must be greater than 0");
834 return NULL;
835 }
836
837 if (timeout <= 0 && timeout != -1)
838 {
839 PyErr_SetString(PyExc_ValueError, "Timeout must be greater than 0");
840 return NULL;
841 }
842
843 if (check_gpio_priv())
844 return NULL;
845
846 Py_BEGIN_ALLOW_THREADS // disable GIL
847 result = blocking_wait_for_edge(gpio, edge, bouncetime, timeout);
848 Py_END_ALLOW_THREADS // enable GIL
849
850 if (result == 0) {
851 Py_RETURN_NONE;
852 } else if (result == -1) {
853 PyErr_SetString(PyExc_RuntimeError, "Conflicting edge detection events already exist for this GPIO channel");
854 return NULL;
855 } else if (result == -2) {
856 PyErr_SetString(PyExc_RuntimeError, "Error waiting for edge");
857 return NULL;
858 } else {
859 return Py_BuildValue("i", channel);
860 }
861
862 }
863
864 // python function value = gpio_function(channel)
865 static PyObject *py_gpio_function(PyObject *self, PyObject *args)
866 {
867 unsigned int gpio;
868 int channel;
869 int f;
870 PyObject *func;
871
872 if (!PyArg_ParseTuple(args, "i", &channel))
873 return NULL;
874
875 if (get_gpio_number(channel, &gpio))
876 return NULL;
877
878 if (mmap_gpio_mem())
879 return NULL;
880
881 f = gpio_function(gpio);
882 switch (f)
883 {
884 case 0 : f = INPUT; break;
885 case 1 : f = OUTPUT; break;
886
887 // ALT 0
888 case 4 : switch (gpio)
889 {
890 case 0 :
891 case 1 :
892 case 2 :
893 case 3 : f = I2C; break;
894
895 case 7 :
896 case 8 :
897 case 9 :
898 case 10 :
899 case 11 : f = SPI; break;
900
901 case 12 :
902 case 13 : f = PWM; break;
903
904 case 14 :
905 case 15 : f = SERIAL; break;
906
907 case 28 :
908 case 29 : f = I2C; break;
909
910 default : f = MODE_UNKNOWN; break;
911 }
912 break;
913
914 // ALT 5
915 case 2 : if (gpio == 18 || gpio == 19) f = PWM; else f = MODE_UNKNOWN;
916 break;
917
918 // ALT 4
919 case 3 : switch (gpio)
920
921 {
922 case 16 :
923 case 17 :
924 case 18 :
925 case 19 :
926 case 20 :
927 case 21 : f = SPI; break;
928 default : f = MODE_UNKNOWN; break;
929 }
930 break;
931
932 default : f = MODE_UNKNOWN; break;
933
934 }
935 func = Py_BuildValue("i", f);
936 return func;
937 }
938
939 // python function setwarnings(state)
940 static PyObject *py_setwarnings(PyObject *self, PyObject *args)
941 {
942 if (!PyArg_ParseTuple(args, "i", &gpio_warnings))
943 return NULL;
944
945 if (setup_error)
946 {
947 PyErr_SetString(PyExc_RuntimeError, "Module not imported correctly!");
948 return NULL;
949 }
950
951 Py_RETURN_NONE;
952 }
953
954 static const char moduledocstring[] = "GPIO functionality of a Raspberry Pi using Python";
955
956 PyMethodDef rpi_gpio_methods[] = {
957 {"setup", (PyCFunction)py_setup_channel, METH_VARARGS | METH_KEYWORDS, "Set up a GPIO channel or list of channels with a direction and (optional) pull/up down control\nchannel - either board pin number or BCM number depending on which mode is set.\ndirection - IN or OUT\n[pull_up_down] - PUD_OFF (default), PUD_UP or PUD_DOWN\n[initial] - Initial value for an output channel"},
958 {"cleanup", (PyCFunction)py_cleanup, METH_VARARGS | METH_KEYWORDS, "Clean up by resetting all GPIO channels that have been used by this program to INPUT with no pullup/pulldown and no event detection\n[channel] - individual channel or list/tuple of channels to clean up. Default - clean every channel that has been used."},
959 {"output", py_output_gpio, METH_VARARGS, "Output to a GPIO channel or list of channels\nchannel - either board pin number or BCM number depending on which mode is set.\nvalue - 0/1 or False/True or LOW/HIGH"},
960 {"input", py_input_gpio, METH_VARARGS, "Input from a GPIO channel. Returns HIGH=1=True or LOW=0=False\nchannel - either board pin number or BCM number depending on which mode is set."},
961 {"setmode", py_setmode, METH_VARARGS, "Set up numbering mode to use for channels.\nBOARD - Use Raspberry Pi board numbers\nBCM - Use Broadcom GPIO 00..nn numbers"},
962 {"getmode", py_getmode, METH_VARARGS, "Get numbering mode used for channel numbers.\nReturns BOARD, BCM or None"},
963 {"add_event_detect", (PyCFunction)py_add_event_detect, METH_VARARGS | METH_KEYWORDS, "Enable edge detection events for a particular GPIO channel.\nchannel - either board pin number or BCM number depending on which mode is set.\nedge - RISING, FALLING or BOTH\n[callback] - A callback function for the event (optional)\n[bouncetime] - Switch bounce timeout in ms for callback"},
964 {"remove_event_detect", py_remove_event_detect, METH_VARARGS, "Remove edge detection for a particular GPIO channel\nchannel - either board pin number or BCM number depending on which mode is set."},
965 {"event_detected", py_event_detected, METH_VARARGS, "Returns True if an edge has occurred on a given GPIO. You need to enable edge detection using add_event_detect() first.\nchannel - either board pin number or BCM number depending on which mode is set."},
966 {"add_event_callback", (PyCFunction)py_add_event_callback, METH_VARARGS | METH_KEYWORDS, "Add a callback for an event already defined using add_event_detect()\nchannel - either board pin number or BCM number depending on which mode is set.\ncallback - a callback function"},
967 {"wait_for_edge", (PyCFunction)py_wait_for_edge, METH_VARARGS | METH_KEYWORDS, "Wait for an edge. Returns the channel number or None on timeout.\nchannel - either board pin number or BCM number depending on which mode is set.\nedge - RISING, FALLING or BOTH\n[bouncetime] - time allowed between calls to allow for switchbounce\n[timeout] - timeout in ms"},
968 {"gpio_function", py_gpio_function, METH_VARARGS, "Return the current GPIO function (IN, OUT, PWM, SERIAL, I2C, SPI)\nchannel - either board pin number or BCM number depending on which mode is set."},
969 {"setwarnings", py_setwarnings, METH_VARARGS, "Enable or disable warning messages"},
970 {NULL, NULL, 0, NULL}
971 };
972
973 #if PY_MAJOR_VERSION > 2
974 static struct PyModuleDef rpigpiomodule = {
975 PyModuleDef_HEAD_INIT,
976 "RPi._GPIO", // name of module
977 moduledocstring, // module documentation, may be NULL
978 -1, // size of per-interpreter state of the module, or -1 if the module keeps state in global variables.
979 rpi_gpio_methods
980 };
981 #endif
982
983 #if PY_MAJOR_VERSION > 2
984 PyMODINIT_FUNC PyInit__GPIO(void)
985 #else
986 PyMODINIT_FUNC init_GPIO(void)
987 #endif
988 {
989 int i;
990 PyObject *module = NULL;
991
992 #if PY_MAJOR_VERSION > 2
993 if ((module = PyModule_Create(&rpigpiomodule)) == NULL)
994 return NULL;
995 #else
996 if ((module = Py_InitModule3("RPi._GPIO", rpi_gpio_methods, moduledocstring)) == NULL)
997 return;
998 #endif
999
1000 define_constants(module);
1001
1002 for (i=0; i<54; i++)
1003 gpio_direction[i] = -1;
1004
1005 // detect board revision and set up accordingly
1006 if (get_rpi_info(&rpiinfo))
1007 {
1008 PyErr_SetString(PyExc_RuntimeError, "This module can only be run on a Raspberry Pi!");
1009 setup_error = 1;
1010 #if PY_MAJOR_VERSION > 2
1011 return NULL;
1012 #else
1013 return;
1014 #endif
1015 }
1016 board_info = Py_BuildValue("{sissssssssss}",
1017 "P1_REVISION",rpiinfo.p1_revision,
1018 "REVISION",&rpiinfo.revision,
1019 "TYPE",rpiinfo.type,
1020 "MANUFACTURER",rpiinfo.manufacturer,
1021 "PROCESSOR",rpiinfo.processor,
1022 "RAM",rpiinfo.ram);
1023 PyModule_AddObject(module, "RPI_INFO", board_info);
1024
1025 if (rpiinfo.p1_revision == 1) {
1026 pin_to_gpio = &pin_to_gpio_rev1;
1027 } else if (rpiinfo.p1_revision == 2) {
1028 pin_to_gpio = &pin_to_gpio_rev2;
1029 } else { // assume model B+ or A+ or 2B
1030 pin_to_gpio = &pin_to_gpio_rev3;
1031 }
1032
1033 rpi_revision = Py_BuildValue("i", rpiinfo.p1_revision); // deprecated
1034 PyModule_AddObject(module, "RPI_REVISION", rpi_revision); // deprecated
1035
1036 // Add PWM class
1037 if (PWM_init_PWMType() == NULL)
1038 #if PY_MAJOR_VERSION > 2
1039 return NULL;
1040 #else
1041 return;
1042 #endif
1043 Py_INCREF(&PWMType);
1044 PyModule_AddObject(module, "PWM", (PyObject*)&PWMType);
1045
1046 #if PY_MAJOR_VERSION < 3 || PY_MINOR_VERSION < 7
1047 if (!PyEval_ThreadsInitialized())
1048 PyEval_InitThreads();
1049 #endif
1050
1051 // register exit functions - last declared is called first
1052 if (Py_AtExit(cleanup) != 0)
1053 {
1054 setup_error = 1;
1055 cleanup();
1056 #if PY_MAJOR_VERSION > 2
1057 return NULL;
1058 #else
1059 return;
1060 #endif
1061 }
1062
1063 if (Py_AtExit(event_cleanup_all) != 0)
1064 {
1065 setup_error = 1;
1066 cleanup();
1067 #if PY_MAJOR_VERSION > 2
1068 return NULL;
1069 #else
1070 return;
1071 #endif
1072 }
1073
1074 #if PY_MAJOR_VERSION > 2
1075 return module;
1076 #else
1077 return;
1078 #endif
1079 }