aboutsummaryrefslogtreecommitdiff
path: root/sandbox/pure-read/read.c
blob: 539933d5aa9ff2662e53a94aade0f2c701747ae9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>

#define BUFFER_SIZE 255
#define IN_MEM (inmem!=0)

typedef struct power_data {
    float power; // Power value
    long ts;     // Associated timestamp
    long nsecs;  // Associated nanosecs
} power_data;

int main(int argc, char *argv[])
{  
    if(argc != 4){
        printf("Usage: %s <device-id> <nread> <inmem>\n\
        \rFor <device-id>, see folder name in /sys/kernel/ina260/",argv[0]);
        exit(1);
    }

    char *deviceid=argv[1];
    int nread=atoi(argv[2]);
    int inmem=atoi(argv[3]);

    if(nread<=0){
        printf("<nread> must be greater than 0\n");
        exit(3);
    }

    // File to read
    char path[255];
    sprintf(path, "/sys/kernel/ina260/%s/power", deviceid);

    // Open file
    int fd;
    char buff[BUFFER_SIZE];
    fd = open(path, O_RDONLY);
    if(fd<0){
        perror(path);
        exit(2);
    }

    // Check if its in memory reading
    power_data *data;
    if(IN_MEM){
        data=malloc(sizeof(power_data)*nread);
        if(data == NULL){
            perror("Cannot allocate enough memory for in memory reads");
            exit(4);
        }
    }

    // Perform reads
    float power=-1;
    struct timespec power_ts;
    clock_gettime(CLOCK_REALTIME, &power_ts);

    printf("startat:%ld\n", power_ts.tv_sec);
    for(int i=0;i<nread;i++){
        read(fd, buff, BUFFER_SIZE);
        // Get power measurement timestamp:
        clock_gettime(CLOCK_REALTIME, &power_ts);
        power=atof(buff);
        if(IN_MEM){
            data[i].power=power;
            data[i].ts=power_ts.tv_sec;
            data[i].nsecs=power_ts.tv_nsec;
        }
        else{
            printf("%s %11ld %10ld> Power is %fW\n",deviceid, power_ts.tv_sec,power_ts.tv_nsec,power);
        }
        lseek(fd,0,SEEK_SET);
    }
    close(fd);

    if(IN_MEM){
        // We only print now (most I/O will happend at the end and this must be visible on the results)
        for(int i=0;i<nread;i++){
            printf("%s %11ld %10ld> Power is %fW\n",deviceid, data[i].ts, data[i].nsecs, data[i].power);
        }
        free(data);
    }
    printf("endat:%ld\n", time(NULL));
    return 0;
}