9daa0f60ca2fe5709c2000f45ee0ae515d5afc05
[contrib/mraa.git] / src / mraa.c
1 /*
2  * Author: Brendan Le Foll <brendan.le.foll@intel.com>
3  * Author: Thomas Ingleby <thomas.c.ingleby@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
26 #define _GNU_SOURCE
27 #if !defined(_XOPEN_SOURCE) || _XOPEN_SOURCE < 600
28 #define _XOPEN_SOURCE 600 /* Get nftw() and S_IFSOCK declarations */
29 #endif
30
31 #include <stddef.h>
32 #include <stdlib.h>
33 #include <sched.h>
34 #include <string.h>
35 #include <pwd.h>
36 #include <glob.h>
37 #include <ftw.h>
38 #include <dirent.h>
39 #include <sys/stat.h>
40 #include <fcntl.h>
41 #include <string.h>
42 #include <stdio.h>
43
44 #include "mraa_internal.h"
45 #include "gpio.h"
46 #include "version.h"
47
48 #define MAX_PLATFORM_NAME_LENGTH 128
49 mraa_board_t* plat = NULL;
50 // static mraa_board_t* current_plat = NULL;
51
52 static char platform_name[MAX_PLATFORM_NAME_LENGTH];
53 mraa_adv_func_t* advance_func;
54
55 const char*
56 mraa_get_version()
57 {
58     return gVERSION;
59 }
60
61 mraa_result_t
62 mraa_set_log_level(int level)
63 {
64     if (level <= 7 && level >= 0) {
65         setlogmask(LOG_UPTO(level));
66         syslog(LOG_DEBUG, "Loglevel %d is set", level);
67         return MRAA_SUCCESS;
68     }
69     syslog(LOG_NOTICE, "Invalid loglevel %d requested", level);
70     return MRAA_ERROR_INVALID_PARAMETER;
71 }
72
73 #if (defined SWIGPYTHON) || (defined SWIG)
74 mraa_result_t
75 #else
76 mraa_result_t __attribute__((constructor))
77 #endif
78 mraa_init()
79 {
80     if (plat != NULL) {
81         return MRAA_ERROR_PLATFORM_ALREADY_INITIALISED;
82     }
83
84     uid_t proc_euid = geteuid();
85     struct passwd* proc_user = getpwuid(proc_euid);
86
87 #ifdef DEBUG
88     setlogmask(LOG_UPTO(LOG_DEBUG));
89 #else
90     setlogmask(LOG_UPTO(LOG_NOTICE));
91 #endif
92
93     openlog("libmraa", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL1);
94     syslog(LOG_NOTICE, "libmraa version %s initialised by user '%s' with EUID %d",
95            mraa_get_version(), (proc_user != NULL) ? proc_user->pw_name : "<unknown>", proc_euid);
96
97 #ifdef SWIGPYTHON
98     // Initialise python threads, this allows use to grab the GIL when we are
99     // required to do so
100     Py_InitializeEx(0);
101     PyEval_InitThreads();
102 #endif
103
104     advance_func = (mraa_adv_func_t*) malloc(sizeof(mraa_adv_func_t));
105     memset(advance_func, 0, sizeof(mraa_adv_func_t));
106
107     mraa_platform_t platform_type;
108 #if defined(X86PLAT)
109     // Use runtime x86 platform detection
110     platform_type = mraa_x86_platform();
111 #elif defined(ARMPLAT)
112     // Use runtime ARM platform detection
113     platform_type = mraa_arm_platform();
114 #else
115 #error mraa_ARCH NOTHING
116 #endif
117
118     if (plat != NULL)
119         plat->platform_type = platform_type;
120
121 #if defined(USBPLAT)
122     // This is a platform extender so create null base platform if one doesn't already exist
123     if (plat == NULL) {
124         plat = (mraa_board_t*) calloc(1, sizeof(mraa_board_t));
125         if (plat != NULL) {
126             plat->platform_type = MRAA_NULL_PLATFORM;
127             plat->platform_name = "Null platform";
128         }
129     }
130     // Now detect sub platform
131     if (plat != NULL) {
132         mraa_platform_t usb_platform_type = mraa_usb_platform_extender(plat);
133         if (plat->platform_type == MRAA_UNKNOWN_PLATFORM && usb_platform_type != MRAA_UNKNOWN_PLATFORM) {
134             plat->platform_type = usb_platform_type;
135         } else {
136             return MRAA_ERROR_PLATFORM_NOT_INITIALISED;
137         }
138     }
139     if (plat == NULL) {
140         printf("mraa: FATAL error, failed to initialise platform\n");
141         return MRAA_ERROR_PLATFORM_NOT_INITIALISED;
142     }
143 #endif
144
145     syslog(LOG_NOTICE, "libmraa initialised for platform '%s' of type %d", mraa_get_platform_name(), mraa_get_platform_type());
146     return MRAA_SUCCESS;
147 }
148
149 void
150 mraa_deinit()
151 {
152     if (plat != NULL) {
153         if (plat->pins != NULL) {
154             free(plat->pins);
155         }
156         mraa_board_t* sub_plat = plat->sub_platform;
157         if (sub_plat != NULL) {
158             if (sub_plat->pins != NULL) {
159                 free(sub_plat->pins);
160             }
161             free(sub_plat);
162         }
163         free(plat);
164
165     }
166     closelog();
167 }
168
169 int
170 mraa_set_priority(const unsigned int priority)
171 {
172     struct sched_param sched_s;
173
174     memset(&sched_s, 0, sizeof(struct sched_param));
175     if (priority > sched_get_priority_max(SCHED_RR)) {
176         sched_s.sched_priority = sched_get_priority_max(SCHED_RR);
177     } else {
178         sched_s.sched_priority = priority;
179     }
180
181     return sched_setscheduler(0, SCHED_RR, &sched_s);
182 }
183
184 mraa_result_t
185 mraa_setup_mux_mapped(mraa_pin_t meta)
186 {
187     int mi;
188
189     for (mi = 0; mi < meta.mux_total; mi++) {
190         mraa_gpio_context mux_i;
191         mux_i = mraa_gpio_init_raw(meta.mux[mi].pin);
192         if (mux_i == NULL) {
193             return MRAA_ERROR_INVALID_HANDLE;
194         }
195         // this function will sometimes fail, however this is not critical as
196         // long as the write succeeds - Test case galileo gen2 pin2
197         mraa_gpio_dir(mux_i, MRAA_GPIO_OUT);
198         mraa_gpio_owner(mux_i, 0);
199
200         if (mraa_gpio_write(mux_i, meta.mux[mi].value) != MRAA_SUCCESS) {
201             mraa_gpio_close(mux_i);
202             return MRAA_ERROR_INVALID_RESOURCE;
203         }
204         mraa_gpio_close(mux_i);
205     }
206
207     return MRAA_SUCCESS;
208 }
209
210 void
211 mraa_result_print(mraa_result_t result)
212 {
213     switch (result) {
214         case MRAA_SUCCESS:
215             fprintf(stdout, "MRAA: SUCCESS\n");
216             break;
217         case MRAA_ERROR_FEATURE_NOT_IMPLEMENTED:
218             fprintf(stdout, "MRAA: Feature not implemented.\n");
219             break;
220         case MRAA_ERROR_FEATURE_NOT_SUPPORTED:
221             fprintf(stdout, "MRAA: Feature not supported by Hardware.\n");
222             break;
223         case MRAA_ERROR_INVALID_VERBOSITY_LEVEL:
224             fprintf(stdout, "MRAA: Invalid verbosity level.\n");
225             break;
226         case MRAA_ERROR_INVALID_PARAMETER:
227             fprintf(stdout, "MRAA: Invalid parameter.\n");
228             break;
229         case MRAA_ERROR_INVALID_HANDLE:
230             fprintf(stdout, "MRAA: Invalid Handle.\n");
231             break;
232         case MRAA_ERROR_NO_RESOURCES:
233             fprintf(stdout, "MRAA: No resources.\n");
234             break;
235         case MRAA_ERROR_INVALID_RESOURCE:
236             fprintf(stdout, "MRAA: Invalid resource.\n");
237             break;
238         case MRAA_ERROR_INVALID_QUEUE_TYPE:
239             fprintf(stdout, "MRAA: Invalid Queue Type.\n");
240             break;
241         case MRAA_ERROR_NO_DATA_AVAILABLE:
242             fprintf(stdout, "MRAA: No Data available.\n");
243             break;
244         case MRAA_ERROR_INVALID_PLATFORM:
245             fprintf(stdout, "MRAA: Platform not recognised.\n");
246             break;
247         case MRAA_ERROR_PLATFORM_NOT_INITIALISED:
248             fprintf(stdout, "MRAA: Platform not initialised.\n");
249             break;
250         case MRAA_ERROR_PLATFORM_ALREADY_INITIALISED:
251             fprintf(stdout, "MRAA: Platform already initialised.\n");
252             break;
253         case MRAA_ERROR_UNSPECIFIED:
254             fprintf(stdout, "MRAA: Unspecified Error.\n");
255             break;
256         default:
257             fprintf(stdout, "MRAA: Unrecognised error.\n");
258             break;
259     }
260 }
261
262
263 mraa_boolean_t
264 mraa_has_sub_platform()
265 {
266     return (plat != NULL) && (plat->sub_platform != NULL);
267 }
268
269 mraa_boolean_t
270 mraa_pin_mode_test(int pin, mraa_pinmodes_t mode)
271 {
272     if (plat == NULL)
273         return 0;
274
275     mraa_board_t* current_plat = plat;
276     if (mraa_is_sub_platform_id(pin)) {
277         current_plat = plat->sub_platform;
278         if (current_plat == NULL) {
279             syslog(LOG_ERR, "mraa_pin_mode_test: Sub platform Not Initialised");
280             return 0;
281         }
282         pin = mraa_get_sub_platform_index(pin);
283     }
284
285     if (current_plat == NULL || current_plat->platform_type == MRAA_UNKNOWN_PLATFORM) {
286         return 0;
287     }
288     if (pin > (current_plat->phy_pin_count - 1) || pin < 0)
289         return 0;
290
291     switch (mode) {
292         case MRAA_PIN_VALID:
293             if (current_plat->pins[pin].capabilites.valid == 1)
294                 return 1;
295             break;
296         case MRAA_PIN_GPIO:
297             if (current_plat->pins[pin].capabilites.gpio == 1)
298                 return 1;
299             break;
300         case MRAA_PIN_PWM:
301             if (current_plat->pins[pin].capabilites.pwm == 1)
302                 return 1;
303             break;
304         case MRAA_PIN_FAST_GPIO:
305             if (current_plat->pins[pin].capabilites.fast_gpio == 1)
306                 return 1;
307             break;
308         case MRAA_PIN_SPI:
309             if (current_plat->pins[pin].capabilites.spi == 1)
310                 return 1;
311             break;
312         case MRAA_PIN_I2C:
313             if (current_plat->pins[pin].capabilites.i2c == 1)
314                 return 1;
315             break;
316         case MRAA_PIN_AIO:
317             if (current_plat->pins[pin].capabilites.aio == 1)
318                 return 1;
319             break;
320         case MRAA_PIN_UART:
321             if (current_plat->pins[pin].capabilites.uart == 1)
322                 return 1;
323             break;
324         default:
325             syslog(LOG_NOTICE, "requested pinmode invalid");
326             break;
327     }
328     return 0;
329 }
330
331 mraa_platform_t
332 mraa_get_platform_type()
333 {
334     if (plat == NULL)
335         return MRAA_UNKNOWN_PLATFORM;
336     return plat->platform_type;
337 }
338
339 int
340 mraa_get_platform_combined_type()
341 {
342     int type = mraa_get_platform_type();
343     int sub_type = mraa_has_sub_platform() ? plat->sub_platform->platform_type : MRAA_UNKNOWN_PLATFORM;
344     return type | (sub_type << 8);
345 }
346
347 unsigned int
348 mraa_adc_raw_bits()
349 {
350     if (plat == NULL)
351         return 0;
352
353     if (plat->aio_count == 0)
354         return 0;
355
356     return plat->adc_raw;
357 }
358
359 unsigned int
360 mraa_get_platform_adc_raw_bits(uint8_t platform_offset)
361 {
362     if (platform_offset == MRAA_MAIN_PLATFORM_OFFSET)
363         return mraa_adc_raw_bits();
364     else {
365         if (!mraa_has_sub_platform())
366             return 0;
367
368         if (plat->sub_platform->aio_count == 0)
369             return 0;
370
371         return plat->sub_platform->adc_raw;
372     }
373 }
374
375
376 unsigned int
377 mraa_adc_supported_bits()
378 {
379     if (plat == NULL)
380         return 0;
381
382     if (plat->aio_count == 0)
383         return 0;
384
385     return plat->adc_supported;
386 }
387
388 unsigned int
389 mraa_get_platform_adc_supported_bits(int platform_offset)
390 {
391     if (platform_offset == MRAA_MAIN_PLATFORM_OFFSET)
392         return mraa_adc_supported_bits();
393     else {
394         if (!mraa_has_sub_platform())
395             return 0;
396
397         if (plat->sub_platform->aio_count == 0)
398             return 0;
399
400         return plat->sub_platform->adc_supported;
401     }
402 }
403
404
405 char*
406 mraa_get_platform_name()
407 {
408     if (plat == NULL) {
409         return NULL;
410     }
411     if (mraa_has_sub_platform()) {
412         snprintf(platform_name, MAX_PLATFORM_NAME_LENGTH, "%s + %s", plat->platform_name, plat->sub_platform->platform_name);
413     } else {
414         strncpy(platform_name, plat->platform_name, MAX_PLATFORM_NAME_LENGTH-1);
415     }
416
417     return platform_name;
418 }
419
420 int
421 mraa_get_i2c_bus_count()
422 {
423     if (plat == NULL) {
424         return -1;
425     }
426     return plat->i2c_bus_count;
427 }
428
429 int
430 mraa_get_i2c_bus_id(unsigned i2c_bus)
431 {
432     if (plat == NULL) {
433         return -1;
434     }
435
436     if (i2c_bus >= plat->i2c_bus_count) {
437         return -1;
438     }
439
440     return plat->i2c_bus[i2c_bus].bus_id;
441 }
442
443 unsigned int
444 mraa_get_pin_count()
445 {
446     if (plat == NULL) {
447         return 0;
448     }
449     return plat->phy_pin_count;
450 }
451
452 unsigned int
453 mraa_get_platform_pin_count(uint8_t platform_offset)
454 {
455     if (platform_offset == MRAA_MAIN_PLATFORM_OFFSET)
456         return mraa_get_pin_count();
457     else {
458         if (mraa_has_sub_platform())
459            return plat->sub_platform->phy_pin_count;
460         else
461            return 0;
462     }
463 }
464
465
466 char*
467 mraa_get_pin_name(int pin)
468 {
469     if (plat == NULL)
470         return 0;
471
472     mraa_board_t* current_plat = plat;
473     if (mraa_is_sub_platform_id(pin)) {
474         current_plat = plat->sub_platform;
475         if (current_plat == NULL) {
476             syslog(LOG_ERR, "mraa_get_pin_name: Sub platform Not Initialised");
477             return 0;
478         }
479         pin = mraa_get_sub_platform_index(pin);
480     }
481
482     if (pin > (current_plat->phy_pin_count - 1) || pin < 0)
483         return NULL;
484     return (char*) current_plat->pins[pin].name;
485 }
486
487 int
488 mraa_get_default_i2c_bus(uint8_t platform_offset)
489 {
490     if (plat == NULL)
491         return -1;
492     if (platform_offset == MRAA_MAIN_PLATFORM_OFFSET) {
493         return plat->def_i2c_bus;
494     } else {
495         if (mraa_has_sub_platform())
496            return plat->sub_platform->def_i2c_bus;
497         else
498            return -1;
499     }
500 }
501
502
503 mraa_boolean_t
504 mraa_file_exist(const char* filename)
505 {
506     glob_t results;
507     results.gl_pathc = 0;
508     glob(filename, 0, NULL, &results);
509     int file_found = results.gl_pathc == 1;
510     globfree(&results);
511     return file_found;
512 }
513
514 mraa_boolean_t
515 mraa_file_contains(const char* filename, const char* content)
516 {
517     mraa_boolean_t found = 0;
518     if ((filename == NULL) || (content == NULL)) {
519         return 0;
520     }
521
522     char* file = mraa_file_unglob(filename);
523     if (file != NULL) {
524         size_t len = 1024;
525         char* line = malloc(len);
526         if (line == NULL) {
527             free(file);
528             return 0;
529         }
530         FILE* fh = fopen(file, "r");
531         if (fh == NULL) {
532             free(file);
533             free(line);
534             return 0;
535         }
536         while ((getline(&line, &len, fh) != -1) && (found == 0)) {
537             if (strstr(line, content)) {
538                 found = 1;
539                 break;
540             }
541         }
542         fclose(fh);
543         free(file);
544         free(line);
545     }
546     return found;
547 }
548
549 mraa_boolean_t
550 mraa_file_contains_both(const char* filename, const char* content, const char* content2)
551 {
552     mraa_boolean_t found = 0;
553     if ((filename == NULL) || (content == NULL)) {
554         return 0;
555     }
556
557     char* file = mraa_file_unglob(filename);
558     if (file != NULL) {
559         size_t len = 1024;
560         char* line = malloc(len);
561         if (line == NULL) {
562             free(file);
563             return 0;
564         }
565         FILE* fh = fopen(file, "r");
566         if (fh == NULL) {
567             free(file);
568             free(line);
569             return 0;
570         }
571         while ((getline(&line, &len, fh) != -1) && (found == 0)) {
572             if (strstr(line, content) && strstr(line, content2)) {
573                 found = 1;
574                 break;
575             }
576         }
577         fclose(fh);
578         free(file);
579         free(line);
580     }
581     return found;
582 }
583
584 char*
585 mraa_file_unglob(const char* filename)
586 {
587     glob_t results;
588     char* res = NULL;
589     results.gl_pathc = 0;
590     glob(filename, 0, NULL, &results);
591     if (results.gl_pathc == 1)
592         res = strdup(results.gl_pathv[0]);
593     globfree(&results);
594     return res;
595 }
596
597 mraa_boolean_t
598 mraa_link_targets(const char* filename, const char* targetname)
599 {
600     int size = 100;
601     int nchars = 0;
602     char* buffer = NULL;
603     while (nchars == 0) {
604         buffer = (char*) realloc(buffer, size);
605         if (buffer == NULL)
606             return 0;
607         nchars = readlink(filename, buffer, size);
608         if (nchars < 0) {
609             free(buffer);
610             return 0;
611         } else {
612             buffer[nchars] = '\0';
613         }
614         if (nchars >= size) {
615             size *= 2;
616             nchars = 0;
617         }
618     }
619     if (strstr(buffer, targetname)) {
620         free(buffer);
621         return 1;
622     } else {
623         free(buffer);
624         return 0;
625     }
626 }
627
628 static int num_i2c_devices = 0;
629
630 static int
631 mraa_count_files(const char* path, const struct stat* sb, int flag, struct FTW* ftwb)
632 {
633     switch (sb->st_mode & S_IFMT) {
634         case S_IFLNK:
635             num_i2c_devices++;
636             break;
637     }
638     return 0;
639 }
640
641 int
642 mraa_find_i2c_bus(const char* devname, int startfrom)
643 {
644     char path[64];
645     int fd;
646     int i = startfrom;
647     int ret = -1;
648
649     // because feeding mraa_find_i2c_bus result back into the function is
650     // useful treat -1 as 0
651     if (startfrom < 0) {
652         startfrom = 0;
653     }
654
655     // find how many i2c buses we have if we haven't already
656     if (num_i2c_devices == 0) {
657         if (nftw("/sys/class/i2c-dev/", &mraa_count_files, 20, FTW_PHYS) == -1) {
658             return -1;
659         }
660     }
661
662     // i2c devices are numbered numerically so 0 must exist otherwise there is
663     // no i2c-dev loaded
664     if (mraa_file_exist("/sys/class/i2c-dev/i2c-0")) {
665         for (i; i < num_i2c_devices; i++) {
666             off_t size, err;
667             snprintf(path, 64, "/sys/class/i2c-dev/i2c-%u/name", i);
668             fd = open(path, O_RDONLY);
669             if (fd < 0) {
670                 break;
671             }
672             size = lseek(fd, 0, SEEK_END);
673             if (size < 0) {
674                 syslog(LOG_WARNING, "mraa: failed to seek i2c filename file");
675                 close(fd);
676                 break;
677             }
678             err = lseek(fd, 0, SEEK_SET);
679             if (err < 0) {
680                 syslog(LOG_WARNING, "mraa: failed to seek i2c filename file");
681                 close(fd);
682                 break;
683             }
684             char* value = malloc(size);
685             if (value == NULL) {
686                 syslog(LOG_ERR, "mraa: failed to allocate memory for i2c file");
687                 close(fd);
688                 break;
689             }
690             ssize_t r = read(fd, value, size);
691             if (r > 0) {
692                 if (strcasestr(value, devname) != NULL) {
693                     free(value);
694                     close(fd);
695                     return i;
696                 }
697             } else {
698                 syslog(LOG_ERR, "mraa: sysfs i2cdev failed");
699             }
700             free(value);
701             close(fd);
702         }
703     } else {
704         syslog(LOG_WARNING, "mraa: no i2c-dev detected, load i2c-dev");
705     }
706
707     return ret;
708 }
709
710 mraa_boolean_t
711 mraa_is_sub_platform_id(int pin_or_bus)
712 {
713     return (pin_or_bus & MRAA_SUB_PLATFORM_MASK) != 0;
714 }
715
716 int
717 mraa_get_sub_platform_id(int pin_or_bus)
718 {
719     return pin_or_bus | MRAA_SUB_PLATFORM_MASK;
720 }
721
722 int
723 mraa_get_sub_platform_index(int pin_or_bus)
724 {
725     return pin_or_bus & (~MRAA_SUB_PLATFORM_MASK);
726 }