summaryrefslogtreecommitdiff
path: root/src/accelerometer/accelerometer.c
blob: beed53c6d341f4f91df88d5e80b5b48f21c31777 (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
/*
 * accelerometer - exports device orientation through property
 *
 * When an "change" event is received on an accelerometer,
 * open its device node, and from the value, as well as the previous
 * value of the property, calculate the device's new orientation,
 * and export it as ID_INPUT_ACCELEROMETER_ORIENTATION.
 *
 * Possible values are:
 * undefined
 * * normal
 * * bottom-up
 * * left-up
 * * right-up
 *
 * The property will be persistent across sessions, and the new
 * orientations can be deducted from the previous one (it allows
 * for a threshold for switching between opposite ends of the
 * orientation).
 *
 * Copyright (C) 2011 Red Hat, Inc.
 * Author:
 *   Bastien Nocera <hadess@hadess.net>
 *
 * orientation_calc() from the sensorfw package
 * Copyright (C) 2009-2010 Nokia Corporation
 * Authors:
 *   Üstün Ergenoglu <ext-ustun.ergenoglu@nokia.com>
 *   Timo Rongas <ext-timo.2.rongas@nokia.com>
 *   Lihan Guo <lihan.guo@digia.com>
 *
 * 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 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <limits.h>
#include <linux/limits.h>
#include <linux/input.h>

#ifdef __UCLIBC__
#include <linux/fcntl.h>
#endif

#include "libudev.h"
#include "libudev-private.h"

/* we must use this kernel-compatible implementation */
#define BITS_PER_LONG (sizeof(unsigned long) * 8)
#define NBITS(x) ((((x)-1)/BITS_PER_LONG)+1)
#define OFF(x)  ((x)%BITS_PER_LONG)
#define BIT(x)  (1UL<<OFF(x))
#define LONG(x) ((x)/BITS_PER_LONG)
#define test_bit(bit, array)    ((array[LONG(bit)] >> OFF(bit)) & 1)

static int debug = 0;

_printf_(6,0)
static void log_fn(struct udev *udev, int priority,
                   const char *file, int line, const char *fn,
                   const char *format, va_list args)
{
        if (debug) {
                fprintf(stderr, "%s: ", fn);
                vfprintf(stderr, format, args);
        } else {
                vsyslog(priority, format, args);
        }
}

typedef enum {
        ORIENTATION_UNDEFINED,
        ORIENTATION_NORMAL,
        ORIENTATION_BOTTOM_UP,
        ORIENTATION_LEFT_UP,
        ORIENTATION_RIGHT_UP
} OrientationUp;

static const char *orientations[] = {
        "undefined",
        "normal",
        "bottom-up",
        "left-up",
        "right-up",
        NULL
};

#define ORIENTATION_UP_UP ORIENTATION_NORMAL

#define DEFAULT_THRESHOLD 250
#define RADIANS_TO_DEGREES 180.0/M_PI
#define SAME_AXIS_LIMIT 5

#define THRESHOLD_LANDSCAPE  25
#define THRESHOLD_PORTRAIT  20

static const char *
orientation_to_string (OrientationUp o)
{
        return orientations[o];
}

static OrientationUp
string_to_orientation (const char *orientation)
{
        int i;

        if (orientation == NULL)
                return ORIENTATION_UNDEFINED;
        for (i = 0; orientations[i] != NULL; i++) {
                if (streq (orientation, orientations[i]))
                        return i;
        }
        return ORIENTATION_UNDEFINED;
}

static OrientationUp
orientation_calc (OrientationUp prev,
                  int x, int y, int z)
{
        int rotation;
        OrientationUp ret = prev;

        /* Portrait check */
        rotation = round(atan((double) x / sqrt(y * y + z * z)) * RADIANS_TO_DEGREES);

        if (abs(rotation) > THRESHOLD_PORTRAIT) {
                ret = (rotation < 0) ? ORIENTATION_LEFT_UP : ORIENTATION_RIGHT_UP;

                /* Some threshold to switching between portrait modes */
                if (prev == ORIENTATION_LEFT_UP || prev == ORIENTATION_RIGHT_UP) {
                        if (abs(rotation) < SAME_AXIS_LIMIT) {
                                ret = prev;
                        }
                }

        } else {
                /* Landscape check */
                rotation = round(atan((double) y / sqrt(x * x + z * z)) * RADIANS_TO_DEGREES);

                if (abs(rotation) > THRESHOLD_LANDSCAPE) {
                        ret = (rotation < 0) ? ORIENTATION_BOTTOM_UP : ORIENTATION_NORMAL;

                        /* Some threshold to switching between landscape modes */
                        if (prev == ORIENTATION_BOTTOM_UP || prev == ORIENTATION_NORMAL) {
                                if (abs(rotation) < SAME_AXIS_LIMIT) {
                                        ret = prev;
                                }
                        }
                }
        }

        return ret;
}

static OrientationUp
get_prev_orientation(struct udev_device *dev)
{
        const char *value;

        value = udev_device_get_property_value(dev, "ID_INPUT_ACCELEROMETER_ORIENTATION");
        if (value == NULL)
                return ORIENTATION_UNDEFINED;
        return string_to_orientation(value);
}

#define SET_AXIS(axis, code_) if (ev[i].code == code_) { if (got_##axis == 0) { axis = ev[i].value; got_##axis = true; } }

/* accelerometers */
static void test_orientation(struct udev *udev,
                             struct udev_device *dev,
                             const char *devpath)
{
        OrientationUp old, new;
        _cleanup_close_ int fd = -1;
        struct input_event ev[64];
        bool got_syn = false;
        bool got_x = false, got_y = false, got_z = false;
        int x = 0, y = 0, z = 0;
        char text[64];

        old = get_prev_orientation(dev);

        fd = open(devpath, O_RDONLY|O_CLOEXEC);
        if (fd < 0)
                return;

        while (1) {
                int i, r;

                r = read(fd, ev, sizeof(struct input_event) * 64);

                if (r < (int) sizeof(struct input_event))
                        return;

                for (i = 0; i < r / (int) sizeof(struct input_event); i++) {
                        if (got_syn) {
                                if (ev[i].type == EV_ABS) {
                                        SET_AXIS(x, ABS_X);
                                        SET_AXIS(y, ABS_Y);
                                        SET_AXIS(z, ABS_Z);
                                }
                        }
                        if (ev[i].type == EV_SYN && ev[i].code == SYN_REPORT)
                                got_syn = true;
                        if (got_x && got_y && got_z)
                                goto read_dev;
                }
        }

read_dev:
        new = orientation_calc(old, x, y, z);
        snprintf(text, sizeof(text),
                 "ID_INPUT_ACCELEROMETER_ORIENTATION=%s", orientation_to_string(new));
        puts(text);
}

static void help(void)
{
        printf("Usage: accelerometer [options] <device path>\n"
               "  --debug         debug to stderr\n"
               "  --help          print this help text\n\n");
}

int main (int argc, char** argv)
{
        struct udev *udev;
        struct udev_device *dev;

        static const struct option options[] = {
                { "debug", no_argument, NULL, 'd' },
                { "help", no_argument, NULL, 'h' },
                {}
        };

        char devpath[PATH_MAX];
        char *devnode;
        struct udev_enumerate *enumerate;
        struct udev_list_entry *list_entry;

        udev = udev_new();
        if (udev == NULL)
                return 1;

        log_open();
        udev_set_log_fn(udev, log_fn);

        /* CLI argument parsing */
        while (1) {
                int option;

                option = getopt_long(argc, argv, "dxh", options, NULL);
                if (option == -1)
                        break;

                switch (option) {
                case 'd':
                        debug = 1;
                        log_set_max_level(LOG_DEBUG);
                        udev_set_log_priority(udev, LOG_DEBUG);
                        break;
                case 'h':
                        help();
                        exit(0);
                default:
                        exit(1);
                }
        }

        if (argv[optind] == NULL) {
                help();
                exit(1);
        }

        /* get the device */
        snprintf(devpath, sizeof(devpath), "/sys/%s", argv[optind]);
        dev = udev_device_new_from_syspath(udev, devpath);
        if (dev == NULL) {
                fprintf(stderr, "unable to access '%s'\n", devpath);
                return 1;
        }

        /* Get the children devices and find the devnode */
        devnode = NULL;
        enumerate = udev_enumerate_new(udev);
        udev_enumerate_add_match_parent(enumerate, dev);
        udev_enumerate_scan_devices(enumerate);
        udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(enumerate)) {
                struct udev_device *device;
                const char *node;

                device = udev_device_new_from_syspath(udev_enumerate_get_udev(enumerate),
                                                      udev_list_entry_get_name(list_entry));
                if (device == NULL)
                        continue;
                /* Already found it */
                if (devnode != NULL) {
                        udev_device_unref(device);
                        continue;
                }

                node = udev_device_get_devnode(device);
                if (node == NULL) {
                        udev_device_unref(device);
                        continue;
                }
                /* Use the event sub-device */
                if (strstr(node, "/event") == NULL) {
                        udev_device_unref(device);
                        continue;
                }

                devnode = strdup(node);
                udev_device_unref(device);
        }

        if (devnode == NULL) {
                fprintf(stderr, "unable to get device node for '%s'\n", devpath);
                return 0;
        }

        log_debug("opening accelerometer device %s", devnode);
        test_orientation(udev, dev, devnode);
        free(devnode);
        log_close();
        return 0;
}