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