maa: add support for enabling pins and pulldowns
[contrib/mraa.git] / src / gpio / gpio.c
1 /*
2  * Author: Thomas Ingleby <thomas.c.ingleby@intel.com>
3  * Author: Brendan Le Foll <brendan.le.foll@intel.com>
4  * Copyright (c) 2014 Intel Corporation.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining
7  * a copy of this software and associated documentation files (the
8  * "Software"), to deal in the Software without restriction, including
9  * without limitation the rights to use, copy, modify, merge, publish,
10  * distribute, sublicense, and/or sell copies of the Software, and to
11  * permit persons to whom the Software is furnished to do so, subject to
12  * the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be
15  * included in all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24  */
25 #include "gpio.h"
26 #include "maa_internal.h"
27
28 #include <stdlib.h>
29 #include <fcntl.h>
30 #include <string.h>
31 #include <unistd.h>
32 #include <poll.h>
33 #include <pthread.h>
34 #include <signal.h>
35 #include <sys/stat.h>
36 #include <sys/mman.h>
37
38 #define SYSFS_CLASS_GPIO "/sys/class/gpio"
39 #define MAX_SIZE 64
40 #define POLL_TIMEOUT
41
42 /**
43  * A structure representing a gpio pin.
44  */
45
46 struct _gpio {
47     /*@{*/
48     int pin; /**< the pin number, as known to the os. */
49     int phy_pin; /**< pin passed to clean init. -1 none and raw*/
50     int value_fp; /**< the file pointer to the value of the gpio */
51     void (* isr)(); /**< the interupt service request */
52     pthread_t thread_id; /**< the isr handler thread id */
53     int isr_value_fp; /**< the isr file pointer on the value */
54     maa_boolean_t owner; /**< If this context originally exported the pin */
55     maa_boolean_t mmap;
56     void *reg;
57     unsigned int reg_sz;
58     unsigned int reg_bit_pos;
59     /*@}*/
60 };
61
62 static maa_result_t
63 maa_gpio_get_valfp(maa_gpio_context dev)
64 {
65     char bu[MAX_SIZE];
66     sprintf(bu, SYSFS_CLASS_GPIO "/gpio%d/value", dev->pin);
67     dev->value_fp = open(bu, O_RDWR);
68     if (dev->value_fp == -1) {
69         return MAA_ERROR_INVALID_RESOURCE;
70     }
71
72     return MAA_SUCCESS;
73 }
74
75 maa_gpio_context
76 maa_gpio_init(int pin)
77 {
78     int pinm = maa_setup_gpio(pin);
79     if (pinm < 0)
80         return NULL;
81
82     maa_gpio_context r = maa_gpio_init_raw(pinm);
83     r->phy_pin = pin;
84     return r;
85 }
86
87 maa_gpio_context
88 maa_gpio_init_raw(int pin)
89 {
90     if (pin < 0)
91         return NULL;
92
93     char bu[MAX_SIZE];
94     int length;
95
96     maa_gpio_context dev = (maa_gpio_context) malloc(sizeof(struct _gpio));
97     memset(dev, 0, sizeof(struct _gpio));
98     dev->value_fp = -1;
99     dev->isr_value_fp = -1;
100     dev->pin = pin;
101     dev->phy_pin = -1;
102
103     char directory[MAX_SIZE];
104     snprintf(directory, MAX_SIZE, SYSFS_CLASS_GPIO "/gpio%d/", dev->pin);
105     struct stat dir;
106     if (stat(directory, &dir) == 0 && S_ISDIR(dir.st_mode)) {
107         //fprintf(stderr, "GPIO Pin already exporting, continuing.\n");
108         dev->owner = 0; // Not Owner
109     } else {
110         int export = open(SYSFS_CLASS_GPIO "/export", O_WRONLY);
111         if (export == -1) {
112             fprintf(stderr, "Failed to open export for writing!\n");
113             return NULL;
114         }
115         length = snprintf(bu, sizeof(bu), "%d", dev->pin);
116         if (write(export, bu, length*sizeof(char)) == -1) {
117             fprintf(stderr, "Failed to write to export\n");
118             close(export);
119             return NULL;
120         }
121         dev->owner = 1;
122         close(export);
123     }
124     return dev;
125 }
126
127 static maa_result_t
128 maa_gpio_write_register(maa_gpio_context dev,int value)
129 {
130     if (value == 1) {
131         *((unsigned *)dev->reg) |= (1<<dev->reg_bit_pos);
132         return MAA_SUCCESS;
133     }
134     *((unsigned *)dev->reg) &= ~(1<<dev->reg_bit_pos);
135     return MAA_SUCCESS;
136 }
137
138 static maa_result_t
139 maa_gpio_wait_interrupt(int fd)
140 {
141     unsigned char c;
142     struct pollfd pfd;
143
144     // setup poll on POLLPRI
145     pfd.fd = fd;
146     pfd.events = POLLPRI;
147
148     // do an initial read to clear interupt
149     read (fd, &c, 1);
150
151     if (fd <= 0) {
152         return MAA_ERROR_INVALID_RESOURCE;
153     }
154
155     // Wait for it forever or until pthread_cancel
156     // poll is a cancelable point like sleep()
157     int x = poll (&pfd, 1, -1);
158
159     // do a final read to clear interupt
160     read (fd, &c, 1);
161
162     return MAA_SUCCESS;
163 }
164
165 static void*
166 maa_gpio_interrupt_handler(void* arg)
167 {
168     maa_gpio_context dev = (maa_gpio_context) arg;
169     maa_result_t ret;
170
171     // open gpio value with open(3)
172     char bu[MAX_SIZE];
173     sprintf(bu, SYSFS_CLASS_GPIO "/gpio%d/value", dev->pin);
174     dev->isr_value_fp = open(bu, O_RDONLY);
175
176     for (;;) {
177         ret = maa_gpio_wait_interrupt(dev->isr_value_fp);
178         if (ret == MAA_SUCCESS) {
179             pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
180 #ifdef SWIGPYTHON
181             // In order to call a python object (all python functions are objects) we
182             // need to aquire the GIL (Global Interpreter Lock). This may not always be
183             // nessecary but especially if doing IO (like print()) python will segfault
184             // if we do not hold a lock on the GIL
185             PyGILState_STATE gilstate = PyGILState_Ensure();
186
187             PyEval_CallObject((PyObject*)dev->isr, NULL);
188
189             PyGILState_Release (gilstate);
190 #else
191             dev->isr();
192 #endif
193             pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
194         } else {
195         // we must have got an error code so die nicely
196             pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
197             close(dev->isr_value_fp);
198             dev->isr_value_fp = -1;
199         return NULL;
200         }
201     }
202 }
203
204 maa_result_t
205 maa_gpio_edge_mode(maa_gpio_context dev, gpio_edge_t mode)
206 {
207     if (dev->value_fp != -1) {
208          close(dev->value_fp);
209          dev->value_fp = -1;
210     }
211
212     char filepath[MAX_SIZE];
213     snprintf(filepath, MAX_SIZE, SYSFS_CLASS_GPIO "/gpio%d/edge", dev->pin);
214
215     int edge = open(filepath, O_RDWR);
216     if (edge == -1) {
217         fprintf(stderr, "Failed to open edge for writing!\n");
218         return MAA_ERROR_INVALID_RESOURCE;
219     }
220
221     char bu[MAX_SIZE];
222     int length;
223     switch(mode) {
224         case MAA_GPIO_EDGE_NONE:
225             length = snprintf(bu, sizeof(bu), "none");
226             break;
227         case MAA_GPIO_EDGE_BOTH:
228             length = snprintf(bu, sizeof(bu), "both");
229             break;
230         case MAA_GPIO_EDGE_RISING:
231             length = snprintf(bu, sizeof(bu), "rising");
232             break;
233         case MAA_GPIO_EDGE_FALLING:
234             length = snprintf(bu, sizeof(bu), "falling");
235             break;
236         default:
237             close(edge);
238             return MAA_ERROR_FEATURE_NOT_IMPLEMENTED;
239     }
240     if (write(edge, bu, length*sizeof(char)) == -1) {
241         fprintf(stderr, "Failed to write to edge\n");
242         close(edge);
243         return MAA_ERROR_INVALID_RESOURCE;
244     }
245
246     close(edge);
247     return MAA_SUCCESS;
248 }
249
250 maa_result_t
251 maa_gpio_isr(maa_gpio_context dev, gpio_edge_t mode, void (*fptr)(void))
252 {
253     // we only allow one isr per maa_gpio_context
254     if (dev->thread_id != 0) {
255         return MAA_ERROR_NO_RESOURCES;
256     }
257
258     maa_gpio_edge_mode(dev, mode);
259     dev->isr = fptr;
260     pthread_create (&dev->thread_id, NULL, maa_gpio_interrupt_handler, (void *) dev);
261
262     return MAA_SUCCESS;
263 }
264
265 maa_result_t
266 maa_gpio_isr_exit(maa_gpio_context dev)
267 {
268     maa_result_t ret = MAA_SUCCESS;
269
270     // wasting our time, there is no isr to exit from
271     if (dev->thread_id == 0 && dev->isr_value_fp == -1) {
272         return ret;
273     }
274
275     // stop isr being useful
276     ret = maa_gpio_edge_mode(dev, MAA_GPIO_EDGE_NONE);
277
278     if ((dev->thread_id != 0) &&
279         (pthread_cancel(dev->thread_id) != 0)) {
280         ret = MAA_ERROR_INVALID_HANDLE;
281     }
282
283     // close the filehandle in case it's still open
284     if (dev->isr_value_fp != -1) {
285           if (close(dev->isr_value_fp) != 0) {
286               ret = MAA_ERROR_INVALID_PARAMETER;
287           }
288     }
289
290 #ifdef SWIGPYTHON
291     // Dereference our Python call back function
292     Py_DECREF(dev->isr);
293 #endif
294
295     // assume our thread will exit either way we just lost it's handle
296     dev->thread_id = 0;
297     dev->isr_value_fp = -1;
298
299     return ret;
300 }
301
302 maa_result_t
303 maa_gpio_mode(maa_gpio_context dev, gpio_mode_t mode)
304 {
305     if (dev->value_fp != -1) {
306          close(dev->value_fp);
307          dev->value_fp = -1;
308     }
309
310     char filepath[MAX_SIZE];
311     snprintf(filepath, MAX_SIZE, SYSFS_CLASS_GPIO "/gpio%d/drive", dev->pin);
312
313     int drive = open(filepath, O_WRONLY);
314     if (drive == -1) {
315         fprintf(stderr, "Failed to open drive for writing!\n");
316         return MAA_ERROR_INVALID_RESOURCE;
317     }
318
319     char bu[MAX_SIZE];
320     int length;
321     switch(mode) {
322         case MAA_GPIO_STRONG:
323             length = snprintf(bu, sizeof(bu), "strong");
324             break;
325         case MAA_GPIO_PULLUP:
326             length = snprintf(bu, sizeof(bu), "pullup");
327             break;
328         case MAA_GPIO_PULLDOWN:
329             length = snprintf(bu, sizeof(bu), "pulldown");
330             break;
331         case MAA_GPIO_HIZ:
332             length = snprintf(bu, sizeof(bu), "hiz");
333             break;
334         default:
335             close(drive);
336             return MAA_ERROR_FEATURE_NOT_IMPLEMENTED;
337     }
338     if (write(drive, bu, length*sizeof(char)) == -1) {
339         fprintf(stderr, "Failed to write to drive mode!\n");
340         close(drive);
341         return MAA_ERROR_INVALID_RESOURCE;
342
343     }
344
345     close(drive);
346     return MAA_SUCCESS;
347 }
348
349 maa_result_t
350 maa_gpio_dir(maa_gpio_context dev, gpio_dir_t dir)
351 {
352     if (dev == NULL) {
353         return MAA_ERROR_INVALID_HANDLE;
354     }
355     if (dev->value_fp != -1) {
356          close(dev->value_fp);
357          dev->value_fp = -1;
358     }
359     char filepath[MAX_SIZE];
360     snprintf(filepath, MAX_SIZE, SYSFS_CLASS_GPIO "/gpio%d/direction", dev->pin);
361
362     int direction = open(filepath, O_RDWR);
363
364     if (direction == -1) {
365         fprintf(stderr, "Failed to open direction for writing!\n");
366         return MAA_ERROR_INVALID_RESOURCE;
367     }
368
369     char bu[MAX_SIZE];
370     int length;
371     int out_switch = 0;
372     switch(dir) {
373         case MAA_GPIO_OUT:
374             length = snprintf(bu, sizeof(bu), "out");
375             out_switch = 1;
376             break;
377         case MAA_GPIO_IN:
378             length = snprintf(bu, sizeof(bu), "in");
379             break;
380         default:
381             close(direction);
382             return MAA_ERROR_FEATURE_NOT_IMPLEMENTED;
383     }
384
385     if (dev->phy_pin >= 0) {
386         maa_result_t swap_res = maa_swap_complex_gpio(dev->phy_pin, out_switch);
387         if (swap_res != MAA_SUCCESS)
388             return swap_res;
389     }
390
391     if (write(direction, bu, length*sizeof(char)) == -1) {
392         fprintf(stderr, "Failed to write to direction\n");
393         close(direction);
394         return MAA_ERROR_INVALID_RESOURCE;
395     }
396
397     close(direction);
398     return MAA_SUCCESS;
399 }
400
401 int
402 maa_gpio_read(maa_gpio_context dev)
403 {
404     if (dev->value_fp == -1) {
405         if (maa_gpio_get_valfp(dev) != MAA_SUCCESS) {
406              fprintf(stderr, "Failed to get value file pointer\n");
407         }
408     }
409     else {
410         // if value_fp is new this is pointless
411         lseek(dev->value_fp, 0, SEEK_SET);
412     }
413     char bu[2];
414     if (read(dev->value_fp, bu, 2*sizeof(char)) != 2) {
415         fprintf(stderr, "Failed to read a sensible value from sysfs");
416     }
417     lseek(dev->value_fp, 0, SEEK_SET);
418     int ret = strtol(bu, NULL, 10);
419
420     return ret;
421 }
422
423 maa_result_t
424 maa_gpio_write(maa_gpio_context dev, int value)
425 {
426     if (dev->mmap == 1)
427         return maa_gpio_write_register(dev,value);
428
429     if (dev->value_fp == -1) {
430         maa_gpio_get_valfp(dev);
431     }
432     if (lseek(dev->value_fp, 0, SEEK_SET) == -1) {
433         return MAA_ERROR_INVALID_RESOURCE;
434     }
435
436     char bu[MAX_SIZE];
437     int length = snprintf(bu, sizeof(bu), "%d", value);
438     if (write(dev->value_fp, bu, length*sizeof(char)) == -1) {
439         return MAA_ERROR_INVALID_HANDLE;
440     }
441
442     return MAA_SUCCESS;
443 }
444
445 static maa_result_t
446 maa_gpio_unexport_force(maa_gpio_context dev)
447 {
448     int unexport = open(SYSFS_CLASS_GPIO "/unexport", O_WRONLY);
449     if (unexport == -1) {
450         fprintf(stderr, "Failed to open unexport for writing!\n");
451         return MAA_ERROR_INVALID_RESOURCE;
452     }
453
454     char bu[MAX_SIZE];
455     int length = snprintf(bu, sizeof(bu), "%d", dev->pin);
456     if (write(unexport, bu, length*sizeof(char)) == -1) {
457         fprintf(stderr, "Failed to write to unexport\n");
458         close(unexport);
459         return MAA_ERROR_INVALID_RESOURCE;
460     }
461
462     close(unexport);
463     maa_gpio_isr_exit(dev);
464     return MAA_SUCCESS;
465 }
466 static maa_result_t
467 maa_gpio_unexport(maa_gpio_context dev)
468 {
469     if(dev->owner) {
470         return maa_gpio_unexport_force(dev);
471     }
472     return MAA_ERROR_INVALID_RESOURCE;
473 }
474
475 maa_result_t
476 maa_gpio_close(maa_gpio_context dev)
477 {
478     if (dev->value_fp != -1) {
479         close(dev->value_fp);
480     }
481     maa_gpio_unexport(dev);
482     free(dev);
483     return MAA_SUCCESS;
484 }
485
486 maa_result_t
487 maa_gpio_owner(maa_gpio_context dev, maa_boolean_t own)
488 {
489     if (dev == NULL)
490         return MAA_ERROR_INVALID_RESOURCE;
491     dev->owner = own;
492     return MAA_SUCCESS;
493 }
494
495 maa_result_t
496 maa_gpio_use_mmaped(maa_gpio_context dev, maa_boolean_t mmap_en)
497 {
498     if (dev ==  NULL) {
499         return MAA_ERROR_INVALID_RESOURCE;
500     }
501
502     if (maa_pin_mode_test(dev->phy_pin, MAA_PIN_FAST_GPIO) == 0)
503         return MAA_ERROR_NO_RESOURCES;
504
505     maa_mmap_pin_t *mmp = maa_setup_mmap_gpio(dev->phy_pin);
506     if (mmp == NULL)
507         return MAA_ERROR_INVALID_RESOURCE;
508
509     if (mmap_en == 1) {
510         if (dev->mmap == 0) {
511             close(dev->value_fp);
512             int fd;
513             fd = open(mmp->mem_dev, O_RDWR);
514             if (fd < 1) {
515                 fprintf(stderr, "Unable to open memory device\n");
516                 return MAA_ERROR_INVALID_RESOURCE;
517             }
518             dev->reg_sz = mmp->mem_sz;
519             dev->reg = mmap(NULL, dev->reg_sz, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
520             dev->reg_bit_pos = mmp->bit_pos;
521             dev->mmap = 1;
522             return MAA_SUCCESS;
523         }
524         return MAA_ERROR_INVALID_PARAMETER;
525     }
526
527     if (mmap_en == 0) {
528         if (dev ->mmap == 1) {
529             munmap(dev->reg, dev->reg_sz);
530             dev->mmap = 0;
531         }
532         return MAA_ERROR_INVALID_PARAMETER;
533     }
534
535     return MAA_SUCCESS;
536 }