xref: /openbmc/openbmc-tools/adcapp/src/adcifc.c (revision 7c0a5dc1)
1  /*****************************************************************
2  *
3  * adcapp.c
4  * Simple interface to read and write adc.
5  *
6  * Author: Rama Rao Bisa <ramab@ami.com>
7  *
8  * Copyright (C) <2019> <American Megatrends International LLC>
9  *
10  *****************************************************************/
11 
12 #include <stdio.h>
13 #include <unistd.h>
14 #include <sys/types.h>
15 #include <sys/stat.h>
16 #include <fcntl.h>
17 #include <sys/ioctl.h>
18 #include <errno.h>
19 #include <string.h>
20 #include <stdint.h>
21 #include "adc.h"
22 #include "adcifc.h"
23 #include "EINTR_wrappers.h"
24 
25 /** \file adcifc.c
26   \brief Source for all adc interface code
27  */
28 
adc_directory_check(char * path)29  static int adc_directory_check(char *path) {
30    int retval = 0;
31    struct stat sb;
32    if (!(stat(path, &sb) == 0 && S_ISDIR(sb.st_mode))) {
33      printf("%s is not exist!\n", path);
34      retval = -1;
35    }
36    return retval;
37  }
38 
sys_get_adc_vol(get_adc_value_t * argp)39 static int sys_get_adc_vol( get_adc_value_t *argp )
40 {
41 	int retval = -1;
42 	int fd;
43 	int tmp;
44         int devid = 0;
45         char stringArray[50];
46         char devpath[50];
47         char val[5];
48         if(argp->channel_num > 15)	retval = -1;
49 #ifdef AST2600_ADCAPP
50         if (argp->channel_num >= 8) {
51           devid = 1;
52           argp->channel_num -= 8;
53         }
54 #endif
55         snprintf(devpath, sizeof(devpath), "/sys/bus/iio/devices/iio:device%d",
56                  devid);
57         retval = adc_directory_check(devpath);
58         if (retval != 0) {
59           return retval;
60         }
61         snprintf(stringArray, sizeof(stringArray), "%s/in_voltage%d_raw",
62                  devpath, argp->channel_num);
63         retval = access(stringArray, F_OK);
64         if(retval != 0)
65 	{
66 		return retval;
67 	}
68 	fd = sigwrap_open(stringArray, O_RDONLY);
69 	if (fd < 0) {
70 		return fd;
71 	}
72 	read(fd, val, 5);
73 	tmp = atoi(val);
74 	(void)sigwrap_close(fd);
75 	argp->channel_value = (uint16_t)(tmp);
76 	retval = 0;
77 	return( retval );
78 }
79 
80 /**
81  * get_adc_val
82  *
83  **/
get_adc_val(int channel,unsigned short * data)84 int get_adc_val( int channel , unsigned short *data)
85 {
86 	get_adc_value_t adc_arg;
87 
88 	/* Set the adc channel to read */
89 	adc_arg.channel_num   = channel;
90 	adc_arg.channel_value = 0;
91 
92 	if ( -1 == sys_get_adc_vol(&adc_arg)) { return -1; }
93 	*data = (unsigned short)(adc_arg.channel_value);
94 
95 	return ( 0 );
96 }
97