Last active
April 13, 2017 08:17
-
-
Save jahir/daeeff25bc20f8a8829dde493b60ba2c to your computer and use it in GitHub Desktop.
Read S0 impulses from mouse events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <fcntl.h> | |
#include <unistd.h> | |
#include <stdio.h> | |
#include <time.h> | |
#include <linux/input.h> | |
#include <stdint.h> | |
// config ///////////////////////// | |
#define IMPULSES_PER_KWH 800 | |
char * button_id[] = { "L", "R", "M" }; | |
////////////////////////////////// | |
double tv_diff(struct timeval * tv1, struct timeval * tv2) { | |
if (tv1->tv_usec < tv2->tv_usec) | |
return (tv2->tv_sec - tv1->tv_sec) + (tv2->tv_usec - tv1->tv_usec)/1e6; | |
else | |
return (tv2->tv_sec - tv1->tv_sec - 1) + (tv1->tv_usec - tv2->tv_usec)/1e6; | |
} | |
#define test_bit(p, n) !!(p[n>>3] & (1u << (n&7))) | |
int isButtonPressed(int fd, unsigned short code) { | |
uint8_t keys[(KEY_MAX<<3)+1]; | |
memset(keys, 0, sizeof(keys)); | |
ioctl(fd, EVIOCGKEY(sizeof(keys)), keys); | |
return test_bit(keys, code); | |
} | |
int main(int argc, char* argv[]) | |
{ | |
char * dev; | |
int fd; | |
ssize_t rc; | |
struct input_event ev; | |
struct timeval prev[3]; | |
if (argc < 2) { | |
fprintf(stderr, "Usage: %s /dev/input/eventX\n", argv[0]); | |
return 1; | |
} | |
dev = argv[1]; | |
memset(prev, 0, sizeof(prev)); | |
printf("using %s\n", dev); | |
if ((fd = open(dev, O_RDWR)) < 0) { | |
perror("open event device"); | |
return 1; | |
} | |
while ((rc = read(fd, &ev, sizeof(ev))) > 0) { | |
char timestr[32]; | |
// printf("event: type %04hx code %04hx value %08x\n", ev.type, ev.code, ev.value); | |
if (ev.type == EV_KEY && (ev.code >= BTN_LEFT && ev.code <= BTN_MIDDLE) && ev.value) { | |
int button = ev.code - BTN_LEFT; | |
if (ev.code == BTN_RIGHT) | |
printf("Tarif: %s\n", isButtonPressed(fd, BTN_MIDDLE) ? "NT" : "HT"); | |
strftime(timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S", localtime(&ev.time.tv_sec) ); | |
printf("%s.%06ld button %s (%d): ", timestr, ev.time.tv_usec, button_id[button], button); | |
if (prev[button].tv_sec) { | |
double tdiff = tv_diff(&prev[button], &ev.time); | |
double p = (3600.0 / IMPULSES_PER_KWH * 1000) / tdiff; | |
printf("t_diff = %0.3f s P = %0.3f W\n", tdiff, p); | |
} else { | |
printf("first impulse\n"); | |
} | |
memcpy(&prev[button], &ev.time, sizeof(prev[button])); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment