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