summaryrefslogtreecommitdiff
path: root/smartpower.c
blob: b60312668ca6e39f80c281bcf350f63047066499 (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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
/*
 * @file smartpower.c: ODROID Smart Power data logger
 *
 * @author: Aliaksei Katovich <aliaksei.katovich@gmail.com>
 *
 * Copyright (C) 2013  Aliaksei Katovich
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 */

#include <linux/types.h>
#include <linux/input.h>
#include <linux/hidraw.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>

#define err(fmt, args...) { \
	fprintf(stderr, "(ee) "fmt, ##args); \
	fprintf(stderr, "(ii) %s:%d: %s, %d\n", __func__, __LINE__, \
		strerror(errno), errno); \
}

#define msg(fmt, args...) fprintf(stderr, "(==) "fmt, ##args)

#define MAX_BUF		65
#define MAX_SLEEP	100 /* us */

#define	FLG_DATA	0x37
#define FLG_STARTSTOP	0x80
#define FLG_STATUS	0x81
#define FLG_ONOFF	0x82
#define FLG_VERSION	0x83

const char *bus_str(int bus)
{
	switch (bus) {
	case BUS_USB:
		return "USB";
		break;
	case BUS_HIL:
		return "HIL";
		break;
	case BUS_BLUETOOTH:
		return "Bluetooth";
		break;
	case BUS_VIRTUAL:
		return "Virtual";
		break;
	default:
		return "Other";
		break;
	}
}

static int smartp_open(const char *dev)
{
	int fd;

	fd = open(dev, O_RDWR | O_NONBLOCK);
	if (fd < 0) {
		err("%s: unable to open device\n", dev);

		if (errno == 13) {
			msg("become root or escalate priviledge\n");
			exit(errno);
		}

		return -errno;
	}

	return fd;
}

static int csv;
static char sep;
static int ts_style;
static double ts_start;

static void smartp_printd(const unsigned char *data)
{
	struct timeval tv;
	double ts;
	unsigned long long ts_sec, ts_usec;

	if (ts_start == 0.0) {
		gettimeofday(&tv, NULL);
		ts_start = (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
		if (ts_style == 0)
			printf("0.0%c%s\n", sep, data);
		else
			printf("[%5u.%06u] %s\n", 0, 0, data);
		return;
	}

	gettimeofday(&tv, NULL);
	ts = (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0 - ts_start;
	if (ts_style == 0) {
		printf("%f%c%s\n", ts, sep, data);
	} else {
		ts_sec = ts;
		ts_usec = (ts - (unsigned long long) ts) * 1000000.0;
		printf("[%5u.%06u] %s\n", (unsigned int) ts_sec,
			(unsigned int) ts_usec, data);
	}
}

static void smartp_csv(unsigned char *data, size_t len, unsigned int start)
{
	int i, space = 0;
	unsigned char *ptr;

	for (i = 0, ptr = &data[start]; *ptr != '\0'; ptr++) {
		if (*ptr == ' ' && space == 0) {
			data[i] = ',';
			space++;
			i++;
		} else if (*ptr == '.' || (*ptr >= 0x30 && *ptr <= 0x39)) {
			data[i] = *ptr;
			space = 0;
			i++;
		}
	}
	data[i] = '\0';
}

#define SMARTP_READ_MAX 100000

static int smartp_read(int fd, unsigned char *buf, size_t len)
{
	int rc = -1;
	int i;

	memset(buf, 0, len);

	for (i = 0; i < SMARTP_READ_MAX; i++) {
		rc = read(fd, buf, len);
		if (rc >= 0)
			break;
	}

	if (rc < 0) {
		err("failed to read %lu bytes\n", (unsigned long)len);
		return rc;
	}

	switch (buf[0]) {
	case 0x37:
		if (!csv) {
			smartp_printd(&buf[2]);
		} else {
			smartp_csv(buf, len, 2);
			smartp_printd(buf);
		}
		break;
	case 0x81:
		printf("Power %s, record %s\n",
			buf[2] == 0 ? "off" : "on",
			buf[1] == 0 ? "off" : "on");
		break;
	case 0x83:
		printf("Version: %s\n", buf);
		break;
	default:
		printf("????:");
		for (i = 0; i < rc; i++)
			printf("%hhx ", buf[i]);
		printf("\n");
	}

	return rc;
}

static int smartp_send(int fd, unsigned char *buf, size_t len)
{
	int rc;

	rc = write(fd, buf, len);
	if (rc < 0) {
		err("cmd=%02x\n", buf[1]);
		return rc;
	}

	return rc;
}

static int smartp_toggle_record(int fd)
{
	int rc;
	unsigned char cmd[2] = { 0x00, FLG_STARTSTOP, };
	unsigned char buf[3];

	rc = smartp_send(fd, cmd, sizeof(cmd));
	if (rc < 0)
		return rc;

	/* update status */
	cmd[1] = FLG_STATUS;
	rc = smartp_send(fd, cmd, sizeof(cmd));
	if (rc < 0)
		return rc;

	return smartp_read(fd, buf, sizeof(buf));
}

static int smartp_toggle_power(int fd)
{
	int rc;
	unsigned char cmd[2] = { 0x00, FLG_ONOFF, };
	unsigned char buf[3];

	rc = smartp_send(fd, cmd, sizeof(cmd));
	if (rc < 0)
		return rc;

	/* update status */
	cmd[1] = FLG_STATUS;
	rc = smartp_send(fd, cmd, sizeof(cmd));
	if (rc < 0)
		return rc;

	usleep(100000); /* wait status update; time gained experimentally */
	return smartp_read(fd, buf, sizeof(buf));
}

#define MAX_VERSION 17

static int smartp_version(int fd)
{
	int rc;
	unsigned char buf[MAX_VERSION];
	unsigned char cmd[2] = { 0x00, FLG_VERSION, };

	rc = smartp_send(fd, cmd, sizeof(cmd));
	if (rc < 0)
		return rc;

	memset(buf, 0, sizeof(buf));
	return smartp_read(fd, buf, sizeof(buf));
}

#define MAX_DATA 34

static int smartp_getdata(int fd)
{
	int rc;
	unsigned char buf[MAX_DATA];
	unsigned char cmd[2] = { 0x00, FLG_DATA, };

	rc = smartp_send(fd, cmd, sizeof(cmd));
	if (rc < 0)
		return rc;

	memset(buf, 0, sizeof(buf));
	return smartp_read(fd, buf, sizeof(buf));
}

#define SMARTP_VENDOR	0x04d8
#define SMARTP_PRODUCT	0x003f

#define HIDRAW_CLASS	"/sys/class/hidraw"

static int smartp_probe(void)
{
	int i = 0;
	int rc;
	int fd = -1;
	struct hidraw_devinfo info;
	char name[80];
	DIR *dir;
	struct dirent *dentry;

	dir = opendir(HIDRAW_CLASS);
	if (!dir) {
		err(HIDRAW_CLASS": failed to open directory\n");
		msg("try to enable CONFIG_HIDRAW in kernel config\n");
		return -errno;
	}

	while ((dentry = readdir(dir))) {
		if (dentry->d_name[0] == '.')
			continue;
		i++;
		snprintf(name, sizeof(name), "/dev/%s", dentry->d_name);
		fd = smartp_open(name);
		if (fd < 0)
			continue;
		rc = ioctl(fd, HIDIOCGRAWINFO, &info);
		if (rc < 0)
			continue;
		if (info.vendor == SMARTP_VENDOR && info.product == SMARTP_PRODUCT) {
			msg("Detected smartp at %s\n", name);
			break;
		}
	}
	closedir(dir);

	if (i == 0)
		msg("smart power device is not connected\n");

	return fd;
}

static int smartp_verbose(int fd, const char *dev)
{
	int rc;
	unsigned char buf[256];
	struct hidraw_devinfo info;

	memset(&info, 0x0, sizeof(info));
	memset(buf, 0x0, sizeof(buf));

	/* Get Raw Name */
	rc = ioctl(fd, HIDIOCGRAWNAME(256), buf);
	if (rc < 0) {
		err("%s: failed to get raw name\n", dev);
		return -errno;
	}
	printf("Raw name: %s\n", buf);

	/* Get Physical Location */
	rc = ioctl(fd, HIDIOCGRAWPHYS(256), buf);
	if (rc < 0) {
		err("%s: failed to get physical location\n", dev);
		return -errno;
	}
	printf("Raw phys: %s\n", buf);

	/* Get Raw Info */
	rc = ioctl(fd, HIDIOCGRAWINFO, &info);
	if (rc < 0) {
		err("%s: failed to get raw info\n", dev);
		return -errno;
	}
	printf("Raw info: bustype %d (%s), vendor 0x%04hx, product 0x%04hx\n",
		info.bustype, bus_str(info.bustype), info.vendor, info.product);
	return 0;
}

static int signal_caught;

void signal_handler(int signum)
{
	signal_caught = signum;
}

static void help(const char *name)
{
	printf("Usage: %s [options]\n", name);
	printf("Options:\n");
	printf("  -h, --help         print this message\n");
	printf("  -p, --power        toggle power supply on/off\n");
	printf("  -r, --record       toggle power consumption recording\n");
	printf("  -v, --verbose      print hidraw details\n");
	printf("  -k, --kernel	     dmesg like time stamps\n");
	printf("  -c, --csv          produce csv output (default raw)\n");
	printf("  -s, --samples <n>  take n samples and exit\n");
	printf("  -d, --dev <dev>    path to hidraw device node\n");
}

static int opt(const char *arg, const char *args, const char *argl)
{
	return (strcmp(arg, args) == 0 || strcmp(arg, argl) == 0);
}

int main(int argc, char **argv)
{
	int fd;
	int i, samples = 0;
	const char *dev = NULL;
	const char *arg;
	int power = 0, record = 0, verbose = 0;

	for (i = 0; i < argc; i++) {
		arg = argv[i];
		if (opt(arg, "-d", "--dev")) {
			i++;
			dev = argv[i];
			continue;
		}
		if (opt(arg, "-s", "--samples")) {
			i++;
			samples = atoi(argv[i]);
			continue;
		}
		if (opt(arg, "-p", "--power")) {
			power = 1;
			continue;
		}
		if (opt(arg, "-r", "--record")) {
			record = 1;
			continue;
		}
		if (opt(arg, "-v", "--verbose")) {
			verbose = 1;
			continue;
		}
		if (opt(arg, "-k", "--kernel")) {
			ts_style = 1;
			csv = 0;
			sep = ' ';
			continue;
		}
		if (opt(arg, "-c", "--csv")) {
			csv = 1;
			sep = ',';
			ts_style = 0;
			continue;
		}
		if (opt(arg, "-h", "--help")) {
			help(argv[0]);
			return 0;
		}
	}

	if (dev)
		fd = smartp_open(dev);
	else
		fd = smartp_probe();

	if (fd < 0)
		return fd;

	if (verbose == 1) {
		smartp_verbose(fd, dev);
		smartp_version(fd);
	}

	if (record == 1)
		return smartp_toggle_record(fd);

	if (power == 1)
		return smartp_toggle_power(fd);

	signal(SIGINT, signal_handler);
	signal(SIGTERM, signal_handler);

	if (samples == 0) {
		while (!signal_caught)
			smartp_getdata(fd);
	} else {
		for (i = 0; i < samples && !signal_caught; i++)
			smartp_getdata(fd);
	}

	close(fd);
	return 0;
}