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