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